Next.js Discord

Discord Forum

Is there any ways to get next-auth session from nextjs middleware without using withAuth?

Answered
Eared Trogon posted this in #help-forum
Open in Discord
Eared TrogonOP
I trying to protect routes programmtically from middleware. But I want to know is how can i get next-auth session inside middleware?
Answered by Eared Trogon
For those who are struggling with trying to get next-auth session from nextjs middleware, you guys can try like this.

import { NextFetchEvent, NextRequest, NextResponse } from "next/server"
import { getToken } from "next-auth/jwt";

export default async function middleware(req: NextRequest, event: NextFetchEvent) {
  const token = await getToken({ req });
  const pathName = req.nextUrl.pathname;
  console.log(token);
  console.log(pathName);

  if(pathName.startsWith("/dashboard") && token == null){
    return NextResponse.redirect(`${req.nextUrl.origin}/`);
  }

  if(pathName === "/" && token){
    return NextResponse.redirect(`${req.nextUrl.origin}/dashboard`);
  }
}

export const config = {
   matcher: ["/dashboard/:path*", "/"] 
}
View full answer

1 Reply

Eared TrogonOP
For those who are struggling with trying to get next-auth session from nextjs middleware, you guys can try like this.

import { NextFetchEvent, NextRequest, NextResponse } from "next/server"
import { getToken } from "next-auth/jwt";

export default async function middleware(req: NextRequest, event: NextFetchEvent) {
  const token = await getToken({ req });
  const pathName = req.nextUrl.pathname;
  console.log(token);
  console.log(pathName);

  if(pathName.startsWith("/dashboard") && token == null){
    return NextResponse.redirect(`${req.nextUrl.origin}/`);
  }

  if(pathName === "/" && token){
    return NextResponse.redirect(`${req.nextUrl.origin}/dashboard`);
  }
}

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