The validate method
Nuxt lets you define a validator method inside your dynamic route component.
-
Type:
FunctionorAsync Function
validate is called every time before navigating to a new route. It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes. This method takes the context object as an argument.
validate({ params, query, store }) {
return true // if the params are valid
return false // will stop Nuxt to render the route and display the error page
}
async validate({ params, query, store }) {
// await operations
return true // if the params are valid
return false // will stop Nuxt to render the route and display the error page
}
You can also return promises:
validate({ params, query, store }) {
return new Promise((resolve) => setTimeout(() => resolve()))
}
Nuxt lets you define a validator method inside your dynamic route component (In this example: pages/users/_id.vue).
If the validate method does not return true, Nuxt will automatically load the 404 error page.
export default {
validate({ params }) {
// Must be a number
return /^\d+$/.test(params.id)
}
}
You can also check some data in your store for example (filled by nuxtServerInit before action):
export default {
validate({ params, store }) {
// Check if `params.id` is an existing category
return store.state.categories.some(category => category.id === params.id)
}
}
You can also throw expected or unexpected errors during validate function execution:
export default {
async validate({ params, store }) {
// Throws a 500 internal server error with custom message
throw new Error('Under Construction!')
}
}
Leoš Literák
Trizotti
Clément Ollivier
Sébastien Chopin
Marcello Bachechi
Rodolphe
Thomas Underwood
Shek Evgeniy
felipesuri
Lukasz Formela
Hugo Torzuoli
Sylvain Marroufin
Kareem Dabbeet
tramplay
Daniel Roe
verebelyicsaba
Adam
Nate Butler
Sandra Rodgers
Arpit Patidar
Matthew Kuehn
Steven DUBOIS
Travis Lindsey
syagawa
Maxime
かる
Al Power
Florent Delerue
quanghm
José Manuel Casani Guerra
Unai Mengual
kazuya kawaguchi
Michael Lynch
Tomachi
pooya parsa
Meir Roth
Brett
Adam Miedema
Thomas Bnt
Kazuki Furukawa
Anthony Ruelle
Christophe Carvalho Vilas-Boas
Roman Harmyder