al1812
al1812

Reputation: 412

NextJs: set status code 404 without redirection

I'm trying to resolve a specific requirement for our web app. We have a page 'Item' that in case of an item sold out should keep showing item but the page's response code must be set to 404. I'm trying something like that:

in pages/[id]/Item.tsx:

static async getInitialProps(ctx) {
   //retrieve item
   if (item.isSoldOut) {
       ctx.res.statusCode = 404;
   }
   //all other stuff
}

but it will automatically redirect to the homepage with status code 302. How to achieve this behavior?

Upvotes: 1

Views: 8094

Answers (1)

dna
dna

Reputation: 2317

Next.js documetation suggest to use getStaticProps or getServerSideProps instead of getInitialProps (https://nextjs.org/docs/api-reference/data-fetching/getInitialProps)

Using getServerSideProps you can do as follow

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
    res.statusCode = 404;
    return { props: {} }
}

Using getInitialProps you can do as follow :

static async getInitialProps({res}) {
    // server side
    if(res) res.statusCode = 404;

    // client side
    return { statusCode : 404 }
}

Upvotes: 6

Related Questions