Next.js Discord

Discord Forum

Failed to verify session in vercel

Unanswered
Polish posted this in #help-forum
Open in Discord
Avatar
PolishOP
i was trying to implement the sateless authentication like this authentication in by doing this
//creating a session by encrypt
export async function createSession(userId: string) {
  const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
  const session = await
    encrypt({ userId, expiresAt })

  cookies().set('session', session, {
    httpOnly: true,
    secure: true,
    expires: expiresAt,
    sameSite: 'lax',
    path: '/',
  })
}

//encrypt function that encrypt the sessionpayload to string 
export async function encrypt(payload: SessionPayload) {
  return new SignJWT(payload)
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('7d')
    .sign(encodedKey)
}

//decrypt function that decrypt the payload 
export async function decrypt(session: string | undefined = '') {
  try {
    const { payload } = await jwtVerify(session, encodedKey, {
      algorithms: ['HS256'],
    })
    return payload
  } catch (error) {
    console.log('Failed to verify session')
  }
}


and in middleware session is verified like this
---------------------
//  Decrypt the session from the cookie
  const cookie = cookies().get('session')?.value
  const session = await decrypt(cookie)
  //  Redirect to /login if the user is not authenticated
  if (isProtectedRoute && !session?.userId) {
    return NextResponse.redirect(new URL('/signin', req.nextUrl))
  }
----------------

fine on local machine
But in vercel error,

Failed to verify session Ft: signature verification failed
at (node_modules/jose/dist/browser/jws/flattened/verify.js:86:0)
at (node_modules/jose/dist/browser/jws/compact/verify.js:15:0)
at (node_modules/jose/dist/browser/jwt/verify.js:5:0)
at (app/lib/session.ts:40:24)
at (middleware.ts:18:18)
at (node_modules/next/dist/esm/server/web/adapter.js:156:0) {
code: 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED',
name: 'Ft',
message: 'signature verification failed'

0 Replies