Add Middleware to Routes in Next JS

Free


How to Add Middleware to Routes in Next JS
Or to Protect a route for auth users in Next JS


React Next JS

Snapshots




First create a middleware.ts file provided below

//Source Code Starting//

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const url = request.nextUrl.clone();

  let isLogin = request.cookies.get("logged");
  if (!isLogin) {
    if (request.nextUrl.pathname.startsWith("/dashboard")) {
      return NextResponse.rewrite(new URL("/", request.url));
    }
  }else{
    if(url.pathname === "/"){
        url.pathname = "/dashboard/home";
        return NextResponse.redirect(url);
    }
  }

  if (request.nextUrl.pathname.startsWith("/signin")) {
    return NextResponse.rewrite(new URL("/", request.url));
  }

}

//Source Code Ending//


Then install cookies-next by using the command
npm i cookies-next

To learn more about cookies next visit
https://www.npmjs.com/package/cookies-next

Then add cookies to your login page
and delete cookies when the user logs out

Related Projects




Watch Add Middleware to Routes in Next JS Installation



Related Projects


Recent Comments

Latest Comments section by users