Comments (3)
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.
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.
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)
from next-auth.
Related Issues (20)
- https://authjs.dev/guides - page not found HOT 1
- @auth/core Attempted import error: 'experimental_customFetch' is not exported from 'oauth4webapi' HOT 1
- Cannot Read Properties of Undefined Error When Importing Mongoose Model in NextAuth Credentials Provider HOT 10
- Domain Changes in Twitter
- Osso Provider Links Dead HOT 1
- Issues getting self-hosted solution working with Apache reverse proxy HOT 4
- Why can User have an undefined id? HOT 1
- Nodemailer: Can't resolve 'crypto' /nodemailer/lib/dkim/sign.js HOT 1
- Nodemailer: usage causes build to fail while dev server works just fine HOT 1
- Invalid MongoDB schema for the prisma adapter (next-auth@beta) HOT 4
- Split configuration is not working
- useSession()'s session.update() does not trigger session update HOT 1
- v5 Beta does not work with Next 15 RC (React 19 RC) - Middleware issue HOT 3
- [v5] Throwing error with custom sign in page leads to undefined route HOT 5
- Strava provider returns Int for providerAccountId but Prisma adapter is expecting a String HOT 1
- Strava provider returns Int for providerAccountId but Prisma adapter is expecting a String
- Custom jwt encryption not working HOT 1
- update() does not work as documented HOT 1
- NextAuth is using an unsupported Node.js API (process.emit) HOT 1
- Firebase adapter Module not found: Can't resolve 'fs' ? HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from next-auth.