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!')
}
}
Clément Ollivier
Daniel Roe
Alex Hirzel
Ajeet Chaulagain
René Eschke
Sébastien Chopin
Nico Devs
Muhammad
Nazaré da Piedade
Naoki Hamada
Tom
Yann Aufray
Anthony Chu
Nuzhat Minhaz
Lucas Portet
Richard Schloss
Xanzhu
bpy
Antony Konstantinidis
Hibariya
Jose Seabra
Eze
Florian LEFEBVRE
Lucas
Julien SEIXAS
Hugo
Sylvain Marroufin
Spencer Cooley
Piotr Zatorski
Vladimir Semenov
Harry Allen
kazuya kawaguchi
Unai Mengual
Hyunseung Lee
Alexandre Chopin
pooya parsa
Nick Medrano
Mosaab Emam
Iljs Путлер Капут
Heitor Ramon Ribeiro
Nero
Yoon Han
Ikko Ashimine
FamCodings
Ayouli
F. Hinkelmann
felipesuri
Christophe Carvalho Vilas-Boas
Leoš Literák
Trizotti
Marcello Bachechi
Rodolphe
Thomas Underwood
Shek Evgeniy
Lukasz Formela
Hugo Torzuoli