How to use middleware in Next.js



Image not found!!

In Next.js, middleware functions can be implemented using custom server functionality provided by the express or http modules. Here's a general guide on how you can use middleware in Next.js:

  1. Set up a custom server:

    Create a server.js file in the root of your Next.js project. This file will be used to configure a custom server using the express module.

    javascript
    // 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(); // Your middleware goes here server.all('*', (req, res) => { return handle(req, res); }); const PORT = process.env.PORT || 3000; server.listen(PORT, (err) => { if (err) throw err; console.log(`> Ready on http://localhost:${PORT}`); }); });
  2. Add Middleware:

    You can add middleware functions before the server.all route handler. Middleware functions can intercept and modify requests and responses. Here's an example of adding a simple middleware function:

    javascript
    // server.js // ... (previous code) // Example middleware function server.use((req, res, next) => { console.log('Middleware executed!'); next(); // Call the next middleware or route handler }); // ... (remaining code)

    You can add as many middleware functions as needed. They will be executed in the order they are added.

  3. Run the Custom Server:

    Update your package.json file to include a script to start the custom server:

    json
    // package.json { // ... "scripts": { "dev": "node server.js", // ... }, // ... }
  4. Start your application:

    Run your Next.js application using the custom server:

    bash
    npm run dev

Now, your custom middleware will be executed for each incoming request. Remember that custom servers are generally used when you need more control over the server setup. If you only need to handle API routes, you can use the built-in API routes feature of Next.js, which doesn't require a custom server.