404 Error Page
A 404 Error Page is a standard response when a user tries to access a page that does not exist. This can happen due to:
- Incorrect or broken links
- Deleted or moved content
- Typographical errors in the URL
A well-designed 404 page enhances user experience by guiding users back to relevant sections instead of leaving them frustrated.
Basic 404 Page Setup
- Create an error.vue file in your project root (not inside the pages directory):
my-nuxt-project/
├── app.vue
├── error.vue <-- Place it here
├── pages/
│ ├── index.vue
│ └── ...
├── layouts/
│ ├── default.vue
│ └── ...
└── ...
Add the following code to your error.vue file:
<!-- error.vue -->
<template>
<div class="min-h-screen flex items-center justify-center bg-primary-50">
<div
class="max-w-md w-full px-6 py-12 bg-white rounded-lg shadow-lg text-center"
>
<div class="mb-8">
<h1 class="text-9xl font-bold text-gray-200">{{ error.statusCode }}</h1>
<div
class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"
>
<BaseCustomIcon name="error" />
</div>
</div>
<!-- Message -->
<h2 class="text-2xl font-bold text-gray-900 mb-4">{{ error.message || "Page not found" }}</h2>
<p class="text-gray-600 mb-8">
The page you are looking for doesn't exist or has been moved.
</p>
<button @click="handleError" class=" bg-primary-500 p-3 rounded-lg" > Back to Home</button>
</div>
</div>
</template>
<script setup>
import { useError } from '#app'
// Get the error from Nuxt's error handling system
const error = useError()
// Function to clear the error and redirect
const handleError = () => {
clearError({ redirect: '/' })
}
</script>
- Create an
check-route.global.jsfile in your middleware folder:
Add the following code to your check-route.global.js file:
// middleware/check-route.global.js
export default defineNuxtRouteMiddleware((to) => {
// For demo purposes, list all your valid routes
// In a real app, you might check against your router's routes
const validRoutes = ['/', '/about', '/contact', '/products']
if (!validRoutes.includes(to.path)) {
// For specific routes you want to check
if (to.path === '/test') {
// This will show the 404 page
throw createError({
statusCode: 404,
message: 'The test page does not exist'
})
}
}
})
The middleware runs automatically once it's created with the .global.js suffix. No additional configuration is needed.