The utilization of the "notFound" prop within getStaticProps does not influence the HTTP status code returned by the page

I recently set up a fresh Next.js application and created the following page:

// /pages/articles/[slug].js

import React from 'react'
import { useRouter } from 'next/router'
import ErrorPage from 'next/error'

const Article = (props) => {
  const router = useRouter()
  if (router.isFallback) {
    return <div>Loading..</div>
  }
  if (!props['data']) {
    return <ErrorPage statusCode={404} />
  }
  return (
    <div>
      Article content
    </div>
  )
}

export default Article

export const getStaticProps = async(context) => {
  const slug = context.params.slug
  const res = ["a", "b", "c"].includes(slug)
    ? {
      props: {
        data: slug
      }
    }
    : {
      props: {},
      notFound: true
    }
  return res
}

export const getStaticPaths = async() =>  {
  return {
    paths: [
      { params: { slug: "a" }},
      { params: { slug: "b" }},
      { params: { slug: "c" }}
    ],
    fallback: true
  }
}

Upon navigating to a non-existent page in the browser (e.g. http://localhost:3000/articles/d), it correctly shows the default Next.js 404 page.

However, the network tab in the browser indicates a status 200 for the main document (the 404 error page). The only resources with a status of 404 are d.json and 404.js.

I believe that even the main document should have a 404 status. The getStaticProps documentation mentions the 'notFound' option:

  • notFound - An optional boolean value to allow the page to return a 404 status and page

In this scenario, despite specifying 'notFound', the page still returns a 200 status instead of 404. Is there an additional step required to return a 404 status?

When disabled, the status is indeed 404.

Answer №1

If you are facing this particular scenario, the recommended approach is to use fallback: 'blocking'.

export const getStaticPaths = async () =>  {
  return {
    paths: [
      { params: { slug: "a" }},
      { params: { slug: "b" }},
      { params: { slug: "c" }}
    ],
    fallback: 'blocking'
  }
}

Unlike using fallback: true, this method will not display a "fallback" version if the page has not been generated yet, which explains the 200 status code you are currently experiencing.

By utilizing fallback: 'blocking', the page will wait for the HTML content to be generated before rendering, akin to server-side rendering. Therefore, if notFound: true is returned from getStaticProps, the appropriate 404 status code will be received for the page request.

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

What causes an "Internal Server Error" when attempting to use data for a database request with AJAX GET/POST in Laravel?

There's a unique issue that I'm struggling to resolve... Every time I drag and drop an event into the calendar, an Ajax Post Request is sent to my controller. The controller then inserts some data into the database with the event name received v ...

I am encountering an issue where the msal-browser login process seems to be frozen at the callback

After successfully installing the msal-browser package, I am able to log in. However, I encounter an issue where the screen gets stuck at the callback URL with a code. The samples provided in the GitHub repository demonstrate returning an access token in ...

"Enhance your website with a unique Bootstrap 5 carousel featuring multiple

As a beginner in Bootstrap, I am currently working on an ecommerce template to learn about Bootstrap 5. I am interested in creating a carousel that displays multiple slides at once, like a products slider with left and right arrows. Is this possible in Bo ...

Errors are caused when attempting to install third-party JS plugins using npm within a foundation project

I am currently exploring projects involving NodeJS and npm. While experimenting with foundation CLI in Foundation 6.4, I decided to install a 3rd Party JS plugin called chart.js from Following their documentation, I ran the command: npm install chart.js ...

Next.js data response not found

My code seems to be having an issue where the data fetched is not displaying on my website. I can see the data when using console.log(data), but nothing shows up when using src={data.img1}. async function getData() { const res = await fetch("http:/ ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

Jump to a specific section on a different page when the links are already equipped with anchors for smooth scrolling

My website has a menu on the home page that scrolls to specific id positions: <li><a href="#event-section">El evento</a></li> <li><a href="#asistentes-section">Asistentes</a></li> <li><a href="#cont ...

Implementing Server-Side API Response Caching in React-Query and Next JS

My server-side rendering setup with react-query is working smoothly. I am aware that react-query stores a cache on the client side to serve data if the query key is fresh and available. Here is the code snippet depicting this setup - // pages/_app.tsx imp ...

The perplexing problem of scrolling in Dojox/mobile/scrollableview

I've noticed some scroll issues with the dojox/mobile/ScrollableView (version 1.10+) in my cordova application, specifically on Android phones. This problem seems to be affecting other widget-based architectures and even some store apps as well. I wou ...

Error encountered in Next.js when defining columns for a MUI data grid

Currently, I am integrating MUI Data Grid into a Next.js app under development. While attempting to define a more intricate column structure, I encountered an error: { field: 'home_address', valueGetter: (value, row) => { retur ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

Sending Three.js meshes to a web worker through JavaScript

I have a collection of objects, which are meshes generated using Three.js, that I need to perform operations on within a web worker. My question is, how can I send these objects to the worker? My understanding is that there's a concept called transfe ...

Is it possible to display multiple qTips for the same target using jQuery qTip2?

I am currently utilizing the jquery qtip2 plugin to generate a mouseover tooltip. Here is the code snippet I am using: $(document).ready(function() { $("#optionalProdsImgPreview_1").qtip({ content: "<img src='http://mysite.com/myimg.jpg&ap ...

To properly handle this file type in React, ensure you have the correct babel loader installed

An error is triggered when trying to compile with webpack. The message indicates that an appropriate loader may be needed to handle this file type. The libraries I am using are: Below are my project files: package.json { "name": "react", "version": ...

The componentDidMount function is not initializing the state

I am trying to access the references from the render function and then set them to the state. Below is my code snippet: class App extends Component { constructor(props) { super(); this.arr = this.generateTimelineArray(); ...

Step-by-step guide on incorporating a hyperlink within a row using @material-ui/data-grid

I am currently using @material-ui/data-grid to showcase some data on my webpage. Each row in the grid must have a link that leads to the next page when clicked. I have all the necessary data ready to be passed, however, I am facing difficulty in creating a ...

Generating a single JSON record in React Native

Need help displaying a single JSON record from an API request on the screen. const [user, setUser] = useState(); const getUserData = async () => { // {headers: {Authorization: "Basic " + base64.encode(username + ":" + passwor ...

using jquery, how can you send multiple parameters in an ajax request

Hello and welcome! I'm having trouble passing parameters through an ajax URL. I am attempting to send multiple data using the jQuery $.ajax method to my PHP script, but I can only pass a single data item when concatenating multiple data entries toget ...

Tips for creating a reusable function in React.js?

I have a script that executes on input focus and passes certain values based on a specific logic. I would like to reuse this script for multiple input fields that trigger the focus event. How can I accomplish this? This is my current script: <input ...

Using React for passing data

In the snippet found in "CameraPage.tsx", there is a logical function that is responsible for fetching camera images. This function simply makes a GET request to search for images stored in the backend, which will later be displayed on the FrontEnd. The op ...