-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
getServerSession not working in middleware using Next.js 13 app directory #7732
Comments
This is expected. Or for now, check out |
With v5 the app and edge compatible middleware will look like this: |
How to deal with this until NextAuth 5 is released? |
If anyone stumbles upon this issue from Google - your only bet here is to make a HTTP Get Request to your app url. /*
* middleware.ts
*/
export function middleware(request: NextRequest) {
const c = cookies();
const allCookies = c
.getAll()
.map((c) => `${c.name}=${c.value}`)
.join("; ");
/**
* If next-auth.session-token is not present, return 401
* (!) IMPORTANT NOTE HERE:
* next-auth likes to use different cookie name for prod (https) so make sure to set a consistent cookie name in your next-auth configuration file (see docs)
*/
if (!c.get("next-auth.session-token")?.value?.trim()) {
return new Response("Unauthorized, log in first", { status: 401 });
}
const headers = {
"Content-Type": "application/json",
Cookie: allCookies,
};
/**
* Send a request to /api/auth/session to get the user session
* process.LOOPBACK_URL can be set as localhost, or your website url
*/
const url = new URL(`/api/auth/session`, process.env.LOOPBACK_URL);
const response = await fetch(url.href, {
headers,
cache: "no-store",
});
if (response.ok) {
// 🔥 check for relevant role/authorization (if necessarry)
if (new Date(session.expires) < new Date()) {
return new Response("Refresh session!", { status: 401 });
}
/**
* Allow the request to continue
*/
return NextResponse.next();
}
return new Response("Unauthorized", { status: 401 });
} |
Is there an implementation with Discord Provider? |
Isn't there some convenient way to get access token from the |
for the people here from google maybe this helps
|
withAuth doesn't accept |
yeah sorry that should be the NextAuth type, NextRequestWithAuth, look at the code in next-auth/src/next/middleware.ts from line 156-EOF
hopefully this helps clarify my original response! |
Question 💬
I can't get the getServerSession to work in a middleware. I'm using the new Next 13 app directory and I placed the
middleware.ts
file in the root of my project. When I try to open a URL that matches the middleware and goes through it, I get the following error:How to reproduce ☕️
Contributing 🙌🏽
Yes, I am willing to help answer this question in a PR
The text was updated successfully, but these errors were encountered: