Skip to content

Unable to setUser on Next.js middleware + next-auth #8508

Closed as not planned
Closed as not planned
@naofalleoagusta

Description

@naofalleoagusta

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which SDK are you using?

@sentry/nextjs

SDK Version

7.57.0

Framework Version

Next.js 13.2.4

Link to Sentry event

https://govtech-procurement.sentry.io/issues/4307368258/?query=is%3Aunresolved&referrer=issue-stream&stream_index=1

SDK Setup

Mostly just from the docs, with the addition of an environment options.

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  // Adjust this value in production, or use tracesSampler for greater control
  tracesSampleRate: 1.0,
  // ...
  // Note: if you want to override the automatic release value, do not set a
  // `release` value here - use the environment variable `SENTRY_RELEASE`, so
  // that it will also get attached to your source maps
  // in development and sample at a lower rate in production
  replaysSessionSampleRate: 0.1,

  // If the entire session is not sampled, use the below sample rate to sample
  // sessions when an error occurs.
  replaysOnErrorSampleRate: 1.0,

  integrations: [
    new Sentry.Replay({
      // Additional SDK configuration goes in here, for example:
      maskAllText: true,
      blockAllMedia: true,
    }),
  ],
})

Steps to Reproduce

Attempting to use setUser on Next.js middleware+withAuth HOC from next-auth.

The middleware setup looking like this :

export default withAuth(
  function middleware(request: NextRequest) {
    const tokenJWT = (request as any)?.nextauth.token as JWT
    const userId = tokenJWT?.profile?.userId
    console.log("console log here", userId)
    if (buyerId) {
      setUser({ id: userId })
    }
    // rest of code
    return NextResponse.next()
  },
  {
    callbacks: {
      authorized: ({ token }) =>!!token
    },
    cookies: customCookies,
    pages: {
      signIn: "/signinpage",
      signOut: "/signoutpage",
      error: "/errorpage",
    },
  }
)

/**
 * Note: Add here if pages requires authentication
 */
export const config = {
  matcher: [
    "/protectedpath"
  ],
}

And yes I have made sure, I have logged in because the middleware only get executed when you are logged in.

Also, I have tried calling the setUser on my client provider using useEffect :

 React.useEffect(() => {
    if (user?.id) {
      setUser({
        id: id,
      })
    }
  }, [buyer?.buyerId])

That didn't work too

Expected Result

The error log should've set the user.id

Actual Result

Sentry doesn't log the user.id

Metadata

Metadata

Assignees

Labels

Package: nextjsIssues related to the Sentry Nextjs SDKPackage: reactIssues related to the Sentry React SDK

Type

No type

Projects

Status

No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions