You can use a validate method in a component to validate the params of a dynamic route before any further data is processed or fetched asynchronously. This validation should always return true to move forward; Nuxt will stop the route and immediately throw a 404 error page if it gets a false Boolean. For example, you want to make sure the ID must be a number:
// pages/users/_id.vue
export default {
validate ({ params }) {
return /^\d+$/.test(params.id)
}
}
So, you will get a 404 page with a This page could not be found message if you request the page with localhost:3000/users/xyz. If you want to customize the 404 message, you can use a throw statement to throw an exception with the Error object, as follows:
// pages/users/_id.vue
export default {
validate ({ params }) {
let test = /^\d+$/.test(params.id)
if (test === false) {
throw new Error('User not found')
}
return true
}
}
You also can use async with the validate method for await...