Better Error Pages in Nuxt — One for Users, One for Developers
You've just defined a beautiful custom error page design in the error.vue file in Nuxt. Everything looks beautiful for the end-user, but from a developer's perspective, all the useful error information is now gone.
So how can we fix that?
In my work, I've come across projects where I, as a developer, face restrictions in my workflow — for example, when a client, due to policy restrictions, can't provide access to their API for local development. In such cases, the only way to test is by deploying the site and hoping for the best.
For a long time, I searched for a way to use a custom or the default error page depending on the environment — and to show the beautiful custom error page only in production. I reached out to Daniel Roe and Alexander Lichter from the Nuxt core team, and they pointed me in the right direction.
Setup
Start by creating a .env file, or add NUXT_SITE_ENV to your existing one. This variable defines the current environment, e.g. development, staging, or production.
NUXT_SITE_ENV=development
Then, add the following to your Nuxt config file:
export default defineNuxtConfig(){
...
hooks: {
'app:resolve': (app) => {
if(env.process.NUXT_SITE_ENV && env.process.NUXT_SITE_ENV !== 'production' ) {
app.errorComponent = './node_modules/nuxt/dist/app/components/nuxt-error-page.vue'
}
}
}
...
}
Here’s what’s happening in the example above:
- On lines 3–4, we hook into app:resolve. Since this hook only runs at build time, we use environment variables to define which environment we're in.
- On line 5, we check if NUXT_SITE_ENV exists and that its value is not production.
- On line 6, we override the default error component path to point to Nuxt’s built-in error page located in node_modules.
With this setup, you can define a different error page per environment, or however you'gd like.
Conclusion
This setup might not suit everyone, but I find it a quick and effective way to provide a polished error page for end-users in production, while keeping a developer-friendly error page for development and staging environments.