Introduction

Nuxt.js allows you to define middleware functions that can be executed globally before rendering a page. These middleware functions can be used for tasks such as authentication, route guarding, or setting common data for multiple pages. In this guide, we'll explore how to use global middleware functions in Nuxt.js and provide sample code to demonstrate the process.


Sample Code

Let's create a Vue.js application with Nuxt.js and define a global middleware function to check if the user is authenticated before rendering any page:


<div id="app">
<nuxt/>
const authMiddleware = ({ store, redirect }) => {
if (!store.state.isAuthenticated) {
// Redirect to the login page if not authenticated
return redirect('/login');
}
};
export default {
router: {
middleware: 'auth'
}
};

In this code:

  • We create a Vue component that includes a `nuxt` element. The `nuxt` element is a placeholder for the content of the current page.
  • We define a global middleware function named `authMiddleware`. This function receives an object with properties such as `store` and `redirect`, which we can use for authentication checks and redirection.
  • Inside the `authMiddleware`, we check if the user is authenticated based on the state stored in the Vuex store. If the user is not authenticated, we use the `redirect` function to navigate to the login page.
  • We specify the global middleware to use for all pages by setting the `middleware` property in the page component to `'auth'`.