question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add a way to set the status code in getServerSideProps

See original GitHub issue

Feature request

When the API call in getServerSideProps returns a 404 or null, I want the route to 404 in the website. I want to be able to manually tell getServerSideProps that an error has occurred and to render a specific status code.

I searched the docs, tried calling res.status(404) and it didn’t work, so I’m filing this feature request

Describe the solution you’d like

The 2nd solution probably fits best from an API design perspective with the rest of Next.js, but the first is probably what most JS developers would expect

Ideal solution

Inside getServerSideProps, if I call res.status(404), the Network tab should show the current document’s status is 404 and the Next.js would render _error or next/error instead of the page it was going to render.

This is ideal, for me at least, because this requires nothing new to learn. It’s how I expected it to work before I filed this issue. However, this might not make as much sense in other cases (getStaticProps).

Alternative solution

Add statusCode to the object we return in getServerSideProps.

For example:

export const getServerSideProps = async ({ query: { id: username }, res }) => {
  const profile = await fetchProfileByUsername(username);
  const profileId = profile?.id ?? null;

  return {
+   statusCode: profileId ? 200 : 404,
    props: {
      profile,
      profileId: profile?.id ?? null,
      username
    }
  };
};

When the status code is > 299, render the appropriate error page with the status code, but default it to 200

Another alternative solution

When you want to manually trigger a 404 error in Ruby on Rails, you raise ActionController::RoutingError inside your controller, for example:

raise ActionController::RoutingError.new('Not Found')

A Next.js version of that might look like this:

import {NotFoundError} from 'next/error';

export const getServerSideProps = async ({ query: { id: username }, res }) => {
  const profile = await fetchProfileByUsername(username);
  const profileId = profile?.id ?? null;
  
   if (!profileId) {
     throw new NotFoundError();
   }

  return {
    props: {
      profile,
      profileId: profile?.id ?? null,
      username
    }
  };
};

This would naturally mean you could render the 404 page easily from non-page parts of your app, too.

My personal preference is I don’t like throwing errors this way, so I put it at the end. But that’s just my opinion

Describe alternatives you’ve considered

I can do this right now, however the status code it returns is still 200 when it really should 404.

import * as React from "react";
import { Page } from "../../src/components/Page";
import { fetchProfileByUsername } from "../../src/lib/api";
import NotFoundPage from "../404";

export const getServerSideProps = async ({ query: { id: username }, res }) => {
  const profile = await fetchProfileByUsername(username);

  return {
    props: {
      profile,
      profileId: profile?.id ?? null,
      username
    }
  };
};

export const ShowProfilePage = ({ profile, username, profileId }) => {
  if (!profile || !profileId) {
    return <NotFoundPage statusCode={404} />;
  }
  return (
    <Page header={<div className="Header-title">{username}</div>}>
      {...notRelevantToCodeSnippet}
    </Page>
  );
};

export default ShowProfilePage;

Additional context

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:17
  • Comments:25 (5 by maintainers)

github_iconTop GitHub Comments

19reactions
timneutkenscommented, Jan 6, 2021

This has been solved in Next.js 10: https://nextjs.org/blog/next-10#notfound-support

14reactions
clauscommented, Apr 3, 2020

Doesn’t res has a statusCode property that you can set?

export const getServerSideProps = async ({ res }) => {
  res.statusCode = 404
  return {
    error: 'oops'
  };
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to return a 404 error in getServerSideProps with Next.js
In your getServerSideProps, where you're fetching the data for your page, you'll just need to add a couple of lines of code:
Read more >
Data Fetching: getServerSideProps - Next.js
Learn how to fetch data on each request with Next.js. ... In some rare cases, you might need to assign a custom status...
Read more >
Refreshing Server-Side Props - Next.js - Josh W Comeau
This brief tutorial shows how to re-fetch the props without doing a full server reload. ... Check that our status code is in...
Read more >
Next.js, redirect to 404 page inside getServerSideProps
You can do that by returning an object like in the below code, with notFound: true . And here is a quote from...
Read more >
Next.js getServerSideProps() Function - GeeksforGeeks
The getServerSideProps() is a method that is used to fetch data from the ... In some unusual circumstances, a special status code may...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found