Server Middleware

Learn how to add middleware to our server routes.

On the front end of our project, we could run code that we may want to execute before navigating to a particular route. This was an additional step between navigation, used to perform a task such as checking if a user is allowed access to a page.

Server middleware

We can also add middleware to our server routes. These middleware files are added to a ~/server/middleware directory, and Nuxt will automatically read any files we add. Middleware will run on every request before any other server routes, meaning we can use it for tasks such as logging, checking header data, and adding extra data to the request object.

Server and router middleware differences

The role of server middleware is a little different from router middleware:

  • Router middleware could perform tasks such as checking if a user is logged in, if not, the navigation could be blocked.

  • Server middleware should not block the request or return anything. Its purpose is to view the request data, extend the request context, or throw an error.

  • Route middleware also runs on the front end of our application, and server middleware runs on the Nitro server side.

Creating server middleware

To create server middleware, we add a JavaScript file to the ~/server/middleware directory:

Get hands-on with 1400+ tech skills courses.