#next-auth 401's with a request body

21 messages · Page 1 of 1 (latest)

robust forge
#

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

This is a list of errors output from NextAuth.js.

glossy adderBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

      🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in <id:customize>

      ✅ 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)
robust forge
#

My test endpoint (returns a session without a body, no session with a body)

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)
robust forge
#

bump 🙏

storm girder
robust forge
#

... the rules could be more explicit if it means 24 hours vs the next actual day

weak garnet
#

In reference to your test endpoint

robust forge
#

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
#
  '@next-auth/prisma-adapter':
    version: 1.0.7(@prisma/[email protected])([email protected])
  next:
  next-auth:
    version: 4.22.1([email protected])([email protected])([email protected])
  next-themes:
    version: 0.2.1([email protected])([email protected])([email protected])
  eslint-config-next:
  /@next-auth/[email protected](@prisma/[email protected])([email protected]):
      next-auth: ^4
      next-auth: 4.22.1([email protected])([email protected])([email protected])
  /[email protected]([email protected])([email protected])([email protected]):
      next: ^12.2.5 || ^13
      next: 13.4.7([email protected])([email protected])
 /[email protected]([email protected])([email protected]):
      '@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 🤯
weak garnet
#

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

robust forge
#

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

weak garnet
#

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

robust forge
#

likewise. Thanks again. I'll stop bugging you now!

weak garnet
#

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

#

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)