1

enter image description here

I want to set response status 404 on my /not-found page. I tried to:

  1. create custom error page in ~/error.vue and throw fatal errors with createError. But it just sends 200
  2. throw fatal errors and use NuxtErrorBoundary. But it doesn't do anything
  3. use setResponseStatus in setup
const event = useRequestEvent()
setResponseStatus(event, 404)
setResponseStatus(event, 404, 'Page Not Found')

But it must be executed (as they say) on the server, so it doesn't always work on setup.

  1. Use middleware in ~/server/middleware):
// setResponseStatus wasn't defined in all ~/server/*
// so I had to import it from here 
import { setResponseStatus } from '../../node_modules/nuxt/dist/app'

export default defineEventHandler((event) => {
  setResponseStatus(event, 404)
})

Which either does nothing or just causes nuxt instance unavailble error.

It shouldn't so complicated, right? Or what am I missing here?

Currently considering handling 404 in nginx instead.

1 Answer 1

1

Using a setup function

<script setup>
if (process.server) {
  const event = useRequestEvent()
  setResponseStatus(event, 404)
}
</script>

Since it only works on server you can wrap it in process.server.


Using (inline) route middleware

<script setup>
definePageMeta({
  middleware: [
    () => {
      const event = useRequestEvent()
      setResponseStatus(event, 404)
    }
  ],
});
</script>

Note that you need a route middleware, not a server middleware. Server middleware run on every request which is probably not what you want.

For the sake of simplicity I made the middleware inline but you can have it in the middleware directory.

Sign up to request clarification or add additional context in comments.

3 Comments

Than you, but: 1. 1st method doesn't work cause it's conditional, for me process.server is always false (note: ssr: true is used) 2. 2nd doesn't work (I copied and pasted the inline version), it's 200 still. Have you used this method yourself before?
Sorry, I had a ssr: false exception for /not-found route. Removed it, but now when I set any route the server side has RangeError [ERR_HTTP_INVALID_STATUS_CODE] Invalid status code: H3Event error and the whole site lags.
There might be something breaking the server. Hard to say without looking at the code but my code works fine for me. How exactly are you setting the route?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.