How to Create a 404 Page in Vue: Simple Guide
To create a 404 page in Vue, define a route with path
/:pathMatch(.*)* in your Vue Router configuration that points to a 404 component. This route catches all unmatched URLs and displays your custom 404 page.Syntax
In Vue Router, you add a catch-all route at the end of your routes array. Use path: '/:pathMatch(.*)*' to match any route not defined earlier. Assign this route to a 404 component that shows the error message.
This ensures users see a friendly page when they visit a URL that doesn't exist in your app.
javascript
const routes = [ // other routes { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound } ];
Example
This example shows a simple Vue app with Vue Router. It has two normal routes and a 404 route that catches all unmatched URLs and displays a friendly message.
javascript
import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; const Home = { template: '<h1>Home Page</h1>' }; const About = { template: '<h1>About Page</h1>' }; const NotFound = { template: '<h1>404 - Page Not Found</h1><p>Sorry, this page does not exist.</p>' }; const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound } ]; const router = createRouter({ history: createWebHistory(), routes }); const app = createApp({}); app.use(router); app.mount('#app');
Output
<h1>404 - Page Not Found</h1><p>Sorry, this page does not exist.</p>
Common Pitfalls
- Placing the 404 route before other routes: The catch-all route must be last, or it will match all URLs and block other routes.
- Using deprecated wildcard syntax: Use
/:pathMatch(.*)*instead of*for Vue Router 4. - Not importing or registering the 404 component: Make sure your 404 component is imported and used correctly in the router.
javascript
/* Wrong: 404 route first - blocks other routes */ const routesWrong = [ { path: '/:pathMatch(.*)*', component: NotFound }, { path: '/', component: Home } ]; /* Right: 404 route last */ const routesRight = [ { path: '/', component: Home }, { path: '/:pathMatch(.*)*', component: NotFound } ];
Quick Reference
- Route path for 404:
/:pathMatch(.*)* - Position: Always last in routes array
- Component: Custom 404 Vue component
- Vue Router version: Vue Router 4 (used with Vue 3)
Key Takeaways
Add a catch-all route with path '/:pathMatch(.*)*' at the end of your Vue Router routes.
Use a dedicated 404 component to show a friendly error message for unmatched URLs.
Ensure the 404 route is last to avoid blocking other routes.
Use Vue Router 4 syntax for catch-all routes in Vue 3 projects.
Test your 404 page by visiting a non-existent URL in your app.