next-auth 401's with a request body
Answered
Common Snipe posted this in #help-forum
Common SnipeOP
I created a minimal curl example to reproduce the error, one with --data and one without to narrow down the issue
curl 'http://localhost:3000/api/test' -H 'Content-Type: application/json' -H 'Cookie: ....'
curl 'http://localhost:3000/api/test' -H 'Content-Type: application/json' -H 'Cookie: ....' --data '{"foo": "bar"}'
In my middleware I can see that req.body is an IncomingStream with data and null without. When there is an IncomingStream my [nextAuth...].ts doesn't trigger the jwt callback and thus I get 401's from my endpoint. I'm super confused - any ideas what could be causing this?
In the failure case I also see this, but the docs and lots of googling haven't helped me narrow down the cause.
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error undefined {
error: {},
url: 'http://localhost:3000/api/auth/session',
message: undefined
}
Thanks in advance! I'll attach the code below
curl 'http://localhost:3000/api/test' -H 'Content-Type: application/json' -H 'Cookie: ....'
curl 'http://localhost:3000/api/test' -H 'Content-Type: application/json' -H 'Cookie: ....' --data '{"foo": "bar"}'
In my middleware I can see that req.body is an IncomingStream with data and null without. When there is an IncomingStream my [nextAuth...].ts doesn't trigger the jwt callback and thus I get 401's from my endpoint. I'm super confused - any ideas what could be causing this?
In the failure case I also see this, but the docs and lots of googling haven't helped me narrow down the cause.
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error undefined {
error: {},
url: 'http://localhost:3000/api/auth/session',
message: undefined
}
Thanks in advance! I'll attach the code below
Answered by Blanc de Hotot
Your environment should warn you but the
getSession function is client-only. You should use getServerSession from next-auth19 Replies
Common SnipeOP
My test endpoint (returns a session without a body, no session with a body)
My middleware looks like this:
and my auth controller looks like this:
import { getSession } from 'next-auth/react';
export default async function handler(req, res) {
const session = await getSession({ req });
res.status(200).json(session);
}My middleware looks like this:
import { withAuth } from 'next-auth/middleware';
import { pathToRegexp } from 'path-to-regexp';
const authenticatedPaths = ['/api/test', '/api/chat', '/api/aws'];
export default withAuth({
pages: {
signIn: '/signin'
},
callbacks: {
async authorized({ token, req }) {
console.log(req.body);
const isPathAuthenticated = authenticatedPaths.some((pathPattern) => {
const pathRegex = pathToRegexp(pathPattern);
return pathRegex.test(req.nextUrl.pathname);
});
if (!token?.email && isPathAuthenticated) {
return false;
} else {
return true;
}
},
},
});and my auth controller looks like this:
export const authOptions: NextAuthOptions = {
providers: [
GitHubProvider({
clientId: process.env.AUTH_GITHUB_ID,
clientSecret: process.env.AUTH_GITHUB_SECRET
})
],
callbacks: {
async jwt({ token, user, trigger }) {
console.log('jwt callback', token, user, trigger)
token.sub = Number(token.sub) as any; //eslint-disable-line
if (user) token.user = user;
return token;
},
async session({ session, token }) {
session.user = (token.user ? token.user : session.user) as Session['user'];
return session;
},
},
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60,
},
adapter: PrismaAdapter(prisma),
debug: true,
pages: {
signIn: '/signin'
}
}
export default NextAuth(authOptions)Common SnipeOP
bump ðŸ™
@Common Snipe bump ðŸ™
Giant panda
Please just be patient - bumps are only acceptable after a full day.
Common SnipeOP
... the rules could be more explicit if it means 24 hours vs the next actual day
Blanc de Hotot
In reference to your test endpoint
Common SnipeOP
this makes sense - vscode doesn't warn about that import -- it does say
Module '"next-auth"' has no exported member 'getServerSession'.ts(2305)
when I try changing it, I get different errors:
`getServerSession` is used in a React Server Component.
https://next-auth.js.org/configuration/nextjs#getServerSession}
https://next-auth.js.org/warnings#EXPERIMENTAL_API
- error Error: Invariant: Method expects to have requestAsyncStorage, none available$ grep next pnpm-lock.yaml
'@next-auth/prisma-adapter':
version: 1.0.7(@prisma/client@4.16.1)(next-auth@4.22.1)
next:
next-auth:
version: 4.22.1(next@13.4.7)(react-dom@18.2.0)(react@18.2.0)
next-themes:
version: 0.2.1(next@13.4.7)(react-dom@18.2.0)(react@18.2.0)
eslint-config-next:
/@next-auth/prisma-adapter@1.0.7(@prisma/client@4.16.1)(next-auth@4.22.1):
next-auth: ^4
next-auth: 4.22.1(next@13.4.7)(react-dom@18.2.0)(react@18.2.0)
/next-auth@4.22.1(next@13.4.7)(react-dom@18.2.0)(react@18.2.0):
next: ^12.2.5 || ^13
next: 13.4.7(react-dom@18.2.0)(react@18.2.0)
/next@13.4.7(react-dom@18.2.0)(react@18.2.0):
'@next/env': 13.4.7
'@next/swc-darwin-arm64': 13.4.7
'@next/swc-darwin-x64': 13.4.7
'@next/swc-linux-arm64-gnu': 13.4.7
'@next/swc-linux-arm64-musl': 13.4.7
'@next/swc-linux-x64-gnu': 13.4.7
'@next/swc-linux-x64-musl': 13.4.7
'@next/swc-win32-arm64-msvc': 13.4.7
'@next/swc-win32-ia32-msvc': 13.4.7
'@next/swc-win32-x64-msvc': 13.4.7^ these are my deps incase useful
ah it's in next-auth/next ---- ok, awesome, that fixed it! thank you!
two questions:
1) why didn't my IDE warn about the import? I should've noticed but ... if there's something up with my env i'd love to fix it
2) why did it work for requests with no body 🤯
two questions:
1) why didn't my IDE warn about the import? I should've noticed but ... if there's something up with my env i'd love to fix it
2) why did it work for requests with no body 🤯
Blanc de Hotot
I wish I could answer your questions but VSC is just tempermental and doesn't always work for some reason
As far as the request with no body goes, I've noticed that nextauth is pretty liberal with it's requests. I recommend implementing logic that tests against both the status code of a response and the content of it
Common SnipeOP
I wish all of the /react packages would throw exceptions if imported in a server context, would likely save a ton of peoples time from silly mistakes
Blanc de Hotot
Oh absolutely. I've spent more than my fair share of hours debugging what ended up being an import issue
I'm just glad we got it working for you
Common SnipeOP
likewise. Thanks again. I'll stop bugging you now!
Blanc de Hotot
No worries! Feel free to ping me if you have any other questions, I'm happy to take a look and try to provide some help
Blanc de Hotot
Also, you should consider marking this forum as answered so that other people can (hopefully) troubleshoot if they have a similar problem
You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)
(if you don't see the option, try refreshing Discord with Ctrl + R)