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!')
}
}
Sébastien Chopin
Nazaré da Piedade
Nobu
川音리오
Maciek Palmowski
Nestor Vera
Daniel Roe
Yue Yang
Jeronimas
Clément Ollivier
Alexander Lichter
N3-rd
Adrien Zaganelli
Mag
Stefan Huber
Olga Bulat
Paiva
Florian Reuschel
Savas Vedova
HIJACK
Vinícius Alves
Kareem Dabbeet
Valentín Costa
Ryan Skinner
Alex Hirzel
Ajeet Chaulagain
René Eschke
Nico Devs
Muhammad
Naoki Hamada
Tom
Yann Aufray
Anthony Chu
Nuzhat Minhaz
Lucas Portet
Richard Schloss
Bobby
bpy
Antony Konstantinidis
Hibariya
Jose Seabra
Eze
Florian Lefebvre
Lucas Recoaro
Julien SEIXAS