Search code examples
reactjsnext.jsmiddlewarevercel

How to get session in Next.js middleware? (error in deploy)


import type { NextFetchEvent, NextRequest } from "next/server";
import { getSession } from "next-auth/react";
import { NextResponse } from "next/server";

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
  const requestForNextAuth = {
    headers: {
      cookie: req.headers.get("cookie"),
    },
  };
  //@ts-ignore
  const session = await getSession({ req: requestForNextAuth });

  if (
    req.nextUrl.pathname.startsWith("/fictions/create") &&
    (!req.cookies.get("~~session") || !session)
  ) {
    return NextResponse.rewrite(new URL("/enter", req.url));
  }

  if (
    req.nextUrl.pathname.includes("/edit") &&
    (!req.cookies.get("~~session") || !session)
  ) {
    return NextResponse.rewrite(new URL("/enter", req.url));
  }

  if (req.nextUrl.pathname.startsWith("/profile") && !session) {
    if (!session) {
      return NextResponse.rewrite(new URL("/enter", req.url));
    }
  }
}

Error Message : "Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation"

It worked well with local but seems I did something wrong because it seems to cause errors in when deploying project.

I want unauthorized people redirected to '/enter' page by using next-auth session. So I used getSession. Is it wrong way to get session in 'edge'? Then what I should do for?


Solution

  • If I understood well you are trying to check in _middleware.js whether the current user is logged in or not ? You cannot use getSession() here.

    Here is my workaround, it's working in local (didn't try in production yet) :

     export async function middleware(req) {
    
        const pathname = req.nextUrl.pathname
    
        const session = await getToken({ req: req, secret: process.env.NEXTAUTH_SECRET }); // I am getting the session here
    
        // Protect protected pages
        if (arrayOfProtectedPaths.includes(pathname)) {
            if (session === null) {
                return NextResponse.redirect("http://localhost:3008/spots/allSpots")
            }
        }
    
        // Prevent logged in user to access to register and sign in 
        if (shouldNotBeUser.includes(pathname)) {
            if (session !== null) {
                return NextResponse.redirect("http://localhost:3008/spots/allSpots")
            }
        }
    }