nextjs
  1. nextjs-middleware

Next.js Middleware

Introduction

If you want to add functionality or common logic between all your pages in Next.js, you can use middleware. Middleware is a function that runs before your Next.js handlers (i.e. getServerSideProps(), getStaticProps()) and can handle operations such as authentication, logging, or modifying the request object.

Syntax

Middleware in Next.js is configured using next.config.js and follows this basic syntax:

module.exports = (phase, {middleware}) => {
  // ...
  middleware: (handler) => (req, res) => {
    // middleware logic here
    return handler(req, res);
  }
  // ...
}

Example

// server.js

const express = require('express');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare()
  .then(() => {
    const server = express();

    // Middleware
    server.use((req, res, next) => {
      console.log(req.method, req.url);
      next();
    });

    // All routes handled by Next.js
    server.get('*', (req, res) => handle(req, res));

    // Start server
    server.listen(3000, err => {
      if (err) throw err;
      console.log('> Ready on http://localhost:3000');
    });
  })
  .catch(err => {
    console.log('An error occurred, unable to start the server');
    console.log(err);
  });

Output

When a request is made to the server, the middleware in the above example will log the HTTP method and URL of the request. For example:

GET /test

Explanation

In the example above, the middleware function logs the HTTP method and URL of the incoming request before passing it along to Next.js. The handler parameter is the Next.js request handler function which will handle the request.

Use

Next.js's middleware can be used for a variety of purposes, including:

  • Adding headers to API requests
  • Logging request information
  • Adding authentication/authorization to routes

Middleware can be used with both server-side and client-side rendering in Next.js, making it a versatile tool for handling common logic between pages.

Important Points

  • Middleware functions in Next.js can handle operations such as authentication or adding headers to requests.
  • Middleware functions must call the next() function to pass control to the next handler.
  • Middleware can be used with both server-side and client-side rendering in Next.js.

Summary

Middleware is a powerful tool in Next.js for adding functionality or common logic between pages. The middleware function runs before handling a request and can modify the request object or handle operations such as authentication. Next.js middleware can be used with both server-side and client-side rendering, making it a useful tool for creating complex applications.

Published on: