ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Api Middlewares in NextJS

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='21' AND `tutorial_submenu`='1752' AND `tutorial_status`=1 LIMIT 1

Api Middlewares in NextJS

In Next.js, middleware functions allow you to process requests before they reach your API routes or pages. You can use middleware for authentication, logging, rate limiting, and modifying request/response objects. There are two main ways to implement middleware in Next.js:


1. Global Middleware (middleware.ts or middleware.js)

  • Placed in the root directory of your Next.js project.

  • Runs on every request before it reaches the API route or page.

  • Uses Next.js Edge API (runs on Edge functions, not Node.js).

Example: Redirect unauthorized users

javascript

export const config = { matcher: ["/dashboard/:path*", "/admin/:path*"],};

This middleware ensures only authenticated users can access /dashboard or /admin.


2. API Route Middleware

  • Applied within specific API routes.

  • Uses standard Express-like middleware functions.

Example: Middleware for API Authentication

javascript

export function withAuth(handler) { return async (req, res) => { const token = req.headers.authorization; if (!token || token !== "your-secret-token") { return res.status(401).json({ message: "Unauthorized" }); } return handler(req, res); };}// Applying middleware to an API routeexport default withAuth(async function handler(req, res) { res.status(200).json({ message: "Welcome to the protected API!" });});

This function wraps API handlers to enforce authentication.


3. Custom Express-like Middleware (Using next-connect)

For more complex middleware chains, next-connect helps organize middleware functions.

Example: Using next-connect

javascript

import nextConnect from "next-connect";const middleware = nextConnect();middleware.use((req, res, next) => { console.log("Request received at:", new Date().toISOString()); next();});export default middleware;

Then apply it to an API route:

javascript

import middleware from "../../middlewares/logger";export default function handler(req, res) { middleware(req, res, () => { res.status(200).json({ message: "Middleware applied!" }); });}


When to Use Each Approach?

  • Global Middleware (middleware.ts): Best for authentication, redirects, or modifying requests before they hit API routes.

  • API Route Middleware: Best for per-route authentication, logging, or validation.

  • next-connect Middleware: Useful for complex middlewares with multiple steps.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql