CodingMSTR LogoCodingMSTR
Add Middleware to Routes in Next JS

Add Middleware to Routes in Next JS

Free

<div><br></div><div><div><b>How to Add Middleware to Routes in Next JS</b></div><div><b>Or to Protect a route for auth users in Next JS</b></div></div>

Category: React, Next JS
Added On: February 26, 2023
Developer: By Praveen
Demo/LiveYoutube Video

For any customization or code setup, feel free to contact us. We also offer deployment on live servers.

For any issues related to downloading, email me at devpraveenkr@gmail.com

Need additional support or customization? Contact me!

Project Screenshots

No screenshots available

Project Description



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

Project Demo Video