Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found header in case the API returns a 404 error. This particular issue has proven to be quite complex.

The structure of our app is as follows:

app/p/auth/
├── layout.jsx
├── loading.jsx
├── password-reset
│   └── [key]
│       ├── components
│       │   ├── index.js
│       │   ├── ResetPassword.jsx
│       │   └── SecurityQuestions.jsx
│       ├── page.jsx
│       └── ResolveComponent.jsx
├── reset-successful
│   └── page.jsx
└── sign-up
    └── page.jsx

The Challenge at Hand

We are facing difficulties when making a request to http://example.com/p/auth/password-reset/[key]. The key must be captured and sent to the REST API for validation purposes. In case the key is not found and notFound() is triggered, we expect a proper 404 HTTP response.

Attempted Solutions

After several attempts, we have found that the only way to return a correct 404 header is by triggering notFound() in app/p/auth/layout.jsx. However, since the layout file is shared among various paths (e.g., app/p/auth/sign-up), isolating the request within app/p/auth/layout.jsx poses a challenge.

We tried isolating the layout.jsx file by deleting the original one and creating a new one in each path individually. Unfortunately, triggering notFound() inside

app/p/auth/password-reset/[key]/layout.jsx
does not result in setting a 404 HTTP header. Instead, it displays the 404 page with a 200 header.

While notFound() successfully sets a 404 header when called from app/p/auth/layout.jsx, it fails to do so when isolated within a sub-folder like

app/p/auth/password-reset/[key]/layout.jsx
. How can we effectively address this issue?

Answer №1

An effective solution suggested in this discussion is to explicitly set the status code. This can be achieved by:

  • Checking for the /404 pathname in middleware.tsx and setting the status to 404
  • Creating a /app/404/page.tsx file if necessary

Here is an example of how your middleware code could look like:

export function middleware(req) {
const url = req.nextUrl;

if (url.pathname === '/404') {
   return  NextResponse.next({
   status: 404,
  });
 }
 return NextResponse.next();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experience the power of Vue Google Chart - Geochart where the chart refreshes seamlessly with data updates, although the legend seems to disappear

I have integrated vue google charts into my nuxt project. Whenever I select a different date, the data gets updated and the computed method in my geochart component correctly reads the new data. However, the legend or color bar at the bottom does not funct ...

Code snippet: Retrieve the previous and upcoming events based on the current date from an array (JavaScript/Angular)

Is there anyone who can assist me with an algorithm? I have a list of events and need to retrieve the next event and previous events based on the current date. For example: I fetch all events from an SQL database like so: events = [ {eventId:1, event ...

In production mode, the Angular/JS Express app is stuck in an endless routing loop, while it functions perfectly in development mode

My webapp is constructed using generator-angular-fullstack. While it functions properly in development mode (grunt serve), I encounter a problem with what appears to be an endless routing loop when switching to production mode (grunt serve:dist). The outp ...

What is the purpose of using a callback like "function(value) {return my_function(value);}" in node.js programming?

Hello, I am brand new to JavaScript so please bear with me if my question seems too simple. Let's say I have a list of strings and I want to filter them based on a function f that takes a string as input and returns a boolean. This approach works: f ...

Is it possible to obtain a user's public URL using the Facebook API in version 2?

In version 1, it is possible to obtain the user's public link by using the following endpoint: /v1.0/me function testAPI() { console.log('Welcome! Fetching your information....'); FB.api('/me', function(response) { ...

Struggling to make changes to a Styled Component in a React application

In a certain file, I have a BaseComponent composed of various other components and being exported. The top level of the BaseComponent contains a wrapper responsible for managing margins. When I export it and attempt to override some styles with: //other fi ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...

A Error occurs if ReactQuill is used without defining the document object

Recently, I embarked on a journey with both next.js and ReactQuill. However, upon running yarn build, an unexpected obstacle arose: info Creating an optimized production build - info Compiled successfully - info Linting and checking validity of types - in ...

The Firefox extension is in need of Google Chrome for compatibility

Currently, I am developing a Firefox extension that displays SSL certificate details. My goal is to only view the certificate information without making any alterations. I am attempting to utilize this specific code example, however, the JavaScript code ha ...

Guide on incorporating a customized HTML tag into ckeditor5

Can someone help me with integrating CKEditor and inserting HTML tag of a clicked image into the editor? I've tried different solutions but haven't been successful. I understand that doing this directly in CKEditor may not be secure. This is a V ...

Is my JavaScript coding accurate?

I'm working on extracting JSON data from my Rest API to display in my application. I'm wondering if the function renderUserState is being called, as the rest of my code seems to be functioning correctly. function testSubmit() { var card = ge ...

Running the Npm start command encounters an error

My terminal is showing the following error message: Q:\clone\node-cloudinary-instagram\node_modules\express\lib\router\route.js:202 throw new Error(msg); Error: Route.get() requires a callback function but go ...

Error: The function concat() is not valid for messagesRef.current

I'm currently developing an app that enables users to interact with AI by asking questions related to the uploaded PDF file. However, I've encountered a problem while interacting with AI on the client side - I keep receiving the error 'TypeE ...

Is there a way to prevent a user who is already logged in from accessing their account on a different browser or tab

My current stack consists of reactjs, nodejs, and redux for user authentication. I am utilizing aws cognito to handle the user authentication process. The main functionality of my app is uploading files from users to an s3 bucket. One of my goals is to p ...

Why does this image slider begin with blankness?

For my recent school project, I created an image slider. However, upon starting the page or reloading it, only the arrows and dots are displayed. View screenshot of the issue Below is the code snippet: // JavaScript function to control the slideshow sho ...

Next.js generates metadata for the runtime environment variable

I am currently utilizing Next.js and attempting to set an environment variable during runtime in order to modify certain metadata. While reviewing the Next.js documentation, it seemed like this should be achievable. However, setting the variable during bui ...

Two distinct controllers: concealing elements through the operation of one of them

I am facing a challenge with my HTML elements: In one form-group, I have the following input: <div class="form-group"> <input type="search" ng-model="search"/> </div> This particular form-group needs to be hidden when another form-g ...

Executing a JavaScript function within a Vue component script

I'm working on a simple component file for submitting a form, along with a JavaScript function to handle an action: <template> <div> <div class="modal-header"> <button type="button" class="close" data-dismi ...

Unpredictable preset inline styles for HTML input elements

While developing a full-stack MERN application, I encountered an unusual issue when inspecting my React UI in Chrome DevTools. If any of these dependencies are playing a role, below are the ones installed that might be contributing to this problem: Tail ...

Displaying JSON data obtained from two separate arrays in AngularJS - is it possible?

I want to display the value of my Json element, "Baru20151","Lama20151","Baru20152","Lama20152", but I'm unsure how to do it. The element is fetched from 2 arrays, for the "Baru20151" elements, "20151" is obtained from the "isimasa" array in my Jso ...