Alexander Nortung
Alexander Nortung

Reputation: 87

Nuxt 3 routing: dynamic routes 404

I am building an application that fetches data from an API. If the API does not find the data I want to display a 404 page.

I have a catch-all route named [...slug] that fetches the data from the API, but how do I render a 404 page without redirecting if the API does not find the data. Redirection is probably the easy fix, but it is not the desired way to do it.

I have looked through https://v3.nuxtjs.org/guide/features/error-handling#errors-during-the-vue-rendering-lifecycle-ssr--spa. But this looks more like a way to catch errors.

I have also seen the following post Nuxt.js and handle API 404 response for dynamic pages. But using the asyncData and error does not seem to work in Nuxt 3.

Upvotes: 1

Views: 6516

Answers (2)

Kealtie
Kealtie

Reputation: 56

You need to add:

throw createError({
  statusCode: 404,
  message: 'not found',
  fatal: true
})

This will make sure it is also handled on static generated sites.

Upvotes: 4

some-user
some-user

Reputation: 4934

You can show an error page programmatically in nuxt3 like this:

throw createError({
  statusCode: 404,
  message: 'not found',
})

e.g.

const { error } = useFetch(...)

if (error.value) {
  throw createError(...)  
}

Upvotes: 2

Related Questions