Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way for me to send the 404 page using the Next.js api routes

Basically, I have an API route /api/signin.js. And I want to accept post requests and return the 404 page when I get a get request. I haven't found any way to return the 404 page without doing something like a redirect. Any help would be appreciated. Thank you.

export default async function Signin(req, res) {
    // /////////////////////////////////////////////////////// //
    // Here is where I want to send the 404 custom 404.js page //
    // /////////////////////////////////////////////////////// //
    if(req.method === "GET") {
        return res.status(404).send();
    }
    
    if(req.method !== "POST") {
        return res.status(404).send();
    }

    try {
        const { cookies, body } = req;
        console.log(req.cookies);

        // Signin logic...
        
    } catch (err) {
        res.status(500).json({ err: "Internal server error" });
    }
}
like image 330
Ojani Avatar asked Sep 18 '25 10:09

Ojani


1 Answers

As a workaround you could use ReactDOMServer's renderToString function

Render a React element to its initial HTML. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.

or ReactDOMServer's renderToStaticMarkup function

Similar to renderToString, except this doesn’t create extra DOM attributes that React uses internally, such as data-reactroot. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes.

// pages/404.js
export default function Custom404() {
  return <h1>404 - Page Not Found</h1>;
}
// pages/api/signin.js
import ReactDOMServer from "react-dom/server";
import NotFound from "../404"; // import your 404 page

export default function Signin(req, res) {
  if (req.method === "GET") {
    return res
      .status(404)
      .send(ReactDOMServer.renderToStaticMarkup(<NotFound />));
  }

  if (req.method !== "POST") {
    return res.status(404).send();
  }

  try {
    const { cookies, body } = req;
    console.log(req.cookies);

    // Signin logic...
  } catch (err) {
    res.status(500).json({ err: "Internal server error" });
  }
}

This way you can send a 404 status code and send an html representation back without a redirect.

like image 91
Bas van der Linden Avatar answered Sep 20 '25 23:09

Bas van der Linden