Next.js Discord

Discord Forum

How do you not return 404 status on a not-found page

Unanswered
Thrianta posted this in #help-forum
Open in Discord
ThriantaOP
I'm trying to create a not-found page which would also be able to load embeds, therefore I don't wanna remember status 404 when accessing an unknown page.

1 Reply

Asiatic Lion
1. Custom "Not Found" Page without 404 Status Code
Instead of using the built-in 404 status handling of Next.js, you will create a regular page that acts as your "Not Found" page but does not automatically send a 404 status back to the client. This allows you to embed other content and handle the page as if it were any other page in your application.

2. Catch-all Routes
Use a catch-all route to capture all undefined routes and redirect them to your custom "Not Found" page. This involves creating a file within your pages directory that looks something like this: [...slug].js. Inside this file, you can control the rendering of your custom "Not Found" page.

3. Example Implementation
Here is a simplified implementation of how you might set this up:

import React from 'react';
import NotFoundPage from '../components/NotFoundPage'; // Assuming you have this component

const CustomNotFound = () => {
  return (
    <NotFoundPage />
  );
};

export async function getServerSideProps(context) {
  // Here you can check if the path should resolve to a real page/component or not
  // Since you want to catch all unknown routes, you might not need specific logic here
  
  return {
    props: {}, // You can pass specific props to your Not Found Page if needed
  };
}

export default CustomNotFound;


components/NotFoundPage.js
Create a NotFoundPage component that will render the content you want to show on your not-found pages, including any embeds or dynamic content.

import React from 'react';

const NotFoundPage = () => {
  return (
    <div>
      <h1>Page Not Found</h1>
      {/* Your embeds or any content here */}
    </div>
  );
};

export default NotFoundPage;

Note:
This might affect SEO negatively, as search engines might not correctly identify missing pages.
Ensure that your application's logic correctly identifies and handles valid routes to prevent all routes from being caught by this catch-all and mistakenly displaying the "Not Found" page.