Coder Social home page Coder Social logo

Comments (3)

MateusTum avatar MateusTum commented on June 2, 2024 1

Same error here!
The workaround that I found was using request cookies to check for session-token and validating it by using an api route. Here is my code:

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

export async function middleware(req: NextRequest) {
  const cookies = req.cookies;

  if (!cookies.get("authjs.session-token")) {
    return NextResponse.redirect(new URL("/login", req.url));
  } else {
    try {
      const sessionResponse = await fetch(
        `${req.nextUrl.origin}/api/auth/session`,
        {
          headers: {
            cookie: req.headers.get("cookie") || "", // Pass cookies to the API route
          },
        }
      );
      if (sessionResponse.status !== 200) {
        throw new Error("Session not found");
      }
    } catch (error) {
      
      console.log(error);
      const response = NextResponse.redirect(new URL("/login", req.url));
      response.cookies.set('authjs.session-token', '', { expires: new Date(0) });
      return response;
    }
  }
  return NextResponse.next();
}

export const config = {
  matcher: "/admin/:path*",
};
// api/auth/session/route.ts
import { auth } from "@/auth";
import { NextResponse } from "next/server";
import { Session } from "next-auth";

export async function GET() {
  const session: Session | null = await auth();
  if (!session) {
    return NextResponse.json({ message: "Auth required" }, { status: 401 });
  }
  return NextResponse.json({ message: "succc" }, { status: 200 });
}

from next-auth.

neil-py avatar neil-py commented on June 2, 2024

Same error here! The workaround that I found was using request cookies to check for session-token and validating it by using an api route. Here is my code:

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

export async function middleware(req: NextRequest) {
  const cookies = req.cookies;

  if (!cookies.get("authjs.session-token")) {
    return NextResponse.redirect(new URL("/login", req.url));
  } else {
    try {
      const sessionResponse = await fetch(
        `${req.nextUrl.origin}/api/auth/session`,
        {
          headers: {
            cookie: req.headers.get("cookie") || "", // Pass cookies to the API route
          },
        }
      );
      if (sessionResponse.status !== 200) {
        throw new Error("Session not found");
      }
    } catch (error) {
      
      console.log(error);
      const response = NextResponse.redirect(new URL("/login", req.url));
      response.cookies.set('authjs.session-token', '', { expires: new Date(0) });
      return response;
    }
  }
  return NextResponse.next();
}

export const config = {
  matcher: "/admin/:path*",
};
// api/auth/session/route.ts
import { auth } from "@/auth";
import { NextResponse } from "next/server";
import { Session } from "next-auth";

export async function GET() {
  const session: Session | null = await auth();
  if (!session) {
    return NextResponse.json({ message: "Auth required" }, { status: 401 });
  }
  return NextResponse.json({ message: "succc" }, { status: 200 });
}

This workaround works so far. I hope a fix will be released soon

from next-auth.

bibblebabl avatar bibblebabl commented on June 2, 2024

I am also experiencing a problem with incorrect req type definition in middleware. Is it the same for you?

No overload matches this call.
  Overload 1 of 4, '(args_0: GetServerSidePropsContext): Promise<Session | null>', gave the following error.
    Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to parameter of type 'GetServerSidePropsContext'.
  Overload 2 of 4, '(args_0: (req: NextAuthRequest, ctx: AppRouteHandlerFnContext) => void | Response | Promise<void | Response>): AppRouteHandlerFn', gave the following error.
    Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to parameter of type '(req: NextAuthRequest, ctx: AppRouteHandlerFnContext) => void | Response | Promise<void | Response>'.
      Type 'Response | null' is not assignable to type 'void | Response | Promise<void | Response>'.
        Type 'null' is not assignable to type 'void | Response | Promise<void | Response>'.ts(2769)
image

from next-auth.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.