tsndr / cloudflare-worker-jwt

A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
MIT License
649 stars 51 forks source link

verify() decode() none works in SSR component. They only works on route or middleware #50

Closed Codename-404 closed 10 months ago

Codename-404 commented 10 months ago

I have a single function to verify and return jwt token. Which works fine on middleware but when I try to get tokendata on a server component it doesn't work. Always returns false.

I am using next js

tsndr commented 10 months ago

Might be related to #49.

Since you've stated that you're using next.js, I want to inform you that this library is only meant to be used with Cloudflare Workers and is not officially compatible with Node.js environments.

Codename-404 commented 10 months ago

No, I mean, I am using cloudflare pages. Not vercel. So yes, it's worker environment. Otherwise I would use Next-auth.

tsndr commented 10 months ago

Since sign() and verify() shouldn't be used on the frontend, because it would leak the secret, the only function that would make sense there would be decode(). In order to decode a JWT, you don't really need to install this library and I'd recommend you doing it with this simple function:

Definition

function decode<T = unknown>(token: string): T | undefined {
    try {
        return JSON.parse(atob(token.split('.')[1]))
    } catch {
        return
    }
}

Usage

type JwtPayload = {
    sub: string
    name: string
    iat: number
}

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'

const payload = decode<JwtPayload>(token)

console.log(payload)

Result

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}