Home
Support Forums

The correct way to redirect to a 404 page from a netlify function?

What is the correct way to redirect to a 404 page from a cloud function? When users request certain URLs we redirect them using a 200 status code to the cloud function, then the cloud function might 301 redirect them to the correct page or 404 them if we really cannot find the page.

this is my redirect code

{
        statusCode: 404,
        headers: {
          Location: '/404.html',
          'Cache-Control': 'no-cache',
        },
        body: JSON.stringify({}),
      }

Problem is that it doesn’t redirect, it just shows a blank page (but it does say 404 in the developer console).

Please advise! Thank you :slight_smile:

I think you can use 301 redirect to redirect to 404 too. Since the end user will see the 404 error page, I think it might work.

I do think that would work but seems wierd to send a 301 to a 404 page! :joy:

Haha, yes, it does seem weird. I had faced a similar issue myself when I was locally trying functions and the 301 had worked in that, so I decided to stay with that for now.

You can try this …

{
  statusCode: 404,
  headers: { Refresh: '0.5;url=/404.html', 'Cache-Control': 'no-cache' },
  body: " "
}
1 Like

Thanks for sharing this, @existo! Knowledge sharing is important to the Support Forums, so we appreciate you chiming in with this information :netliconfetti: