Welcome to this tutorial on Middleware in Nuxt.js! Middleware are a powerful feature that lets you execute custom functions before rendering a page or group of pages. This can be useful in a variety of situations, such as user authentication or data pre-fetching.
Throughout this tutorial, you will learn:
- What middleware is in the context of Nuxt.js
- How to create and use middleware
- How to apply middleware to specific routes or globally
Prerequisites: Basic understanding of JavaScript and VueJS is needed. Familiarity with Nuxt.js is beneficial but not mandatory.
Middleware in Nuxt.js is a function that gets executed before rendering a page or a group of pages (layouts). You can use middleware to check whether a user is authenticated, pre-fetch data before rendering, or perform other necessary checks.
Let's create our first middleware. Middleware files are stored in the middleware
directory in the root of your project.
Create a file named auth.js
in the middleware
directory and add the following code:
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.authenticated) {
return redirect('/login')
}
}
This simple middleware checks if the user is authenticated. If not, it redirects the user to the login page.
To use a middleware, you can add a middleware property in your route object in nuxt.config.js
:
router: {
middleware: 'auth'
}
Or, you can add it in the Vue file:
export default {
middleware: 'auth'
}
You can also set middleware in the layout file, which will be applied to all the routes of that layout.
Let's create a middleware that logs the route name before navigating to a page:
middleware/logRoute.js
:
export default function ({ route }) {
console.log(`Navigating to route: ${route.name}`)
}
This middleware logs the name of the route you are navigating to. To use it, add it to the middleware property in your nuxt.config.js
file or Vue file.
In this tutorial, we have learned about middleware in Nuxt.js, how to create it, and how to use it. We've also seen how to apply middleware to specific routes or globally.
Next steps for learning can be exploring more complex middleware use cases, such as fetching data from an API or handling errors.
You can find more information in the Nuxt.js documentation.
Solution:
javascript
export default function () {
console.log(`Page rendered at: ${new Date().toLocaleString()}`)
}
This middleware logs the current time each time a page is rendered.
Exercise 2: Create a middleware that checks if a user is an admin. If not, redirect to a 'not-authorized' page.
Solution:
javascript
export default function ({ store, redirect }) {
if (!store.state.user.isAdmin) {
return redirect('/not-authorized')
}
}
This middleware checks if the user is an admin. If not, it redirects to a 'not-authorized' page.
Exercise 3: Create a middleware that fetches a list of posts from an API before rendering a page.
javascript
export default async function ({ store }) {
if (!store.state.posts.length) {
const posts = await fetch('https://jsonplaceholder.typicode.com/posts')
store.commit('setPosts', await posts.json())
}
}
Remember, practice makes perfect. Keep trying different scenarios and use cases to fully understand middleware in Nuxt.js.