Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

How to use the local API to get the user from the payload-token?

default discord avatar
zenwhiskersmeowlast year
7

I am using the local API server-side in nextjs server action and server components. I can get the payload-token from cookies(). Now I'd like to know how I can get the user from the local payload API, only if the JWT is untampered.

  • default discord avatar
    gfwgfwlast year

    payload.auth({ headers: request.headers })

  • default discord avatar
    zenwhiskersmeowlast year

    Thanks, I went to multiple cities and cried wolf!! Rly wanted to get unblocked on a Friday night. Hopefully it helps people that the issue is in two places.



    payload.auth() taking the headers is nice!! can trust payload for all the JWT verification, checking for tampering, extracting the claims... nice indeed



    good work everyone 🙂



    its working great

  • default discord avatar
    gfwgfwlast year

    also there are some utils in payload, you can decrypt the jwt manually

  • default discord avatar
    zenwhiskersmeowlast year

    where is that? i thought i had to pnpm add jose and use (await getPayload().secret) as the secret



    it seemed like payload wouldve given us something like this so i was suspicious i was duplicating effort



    even though my problem is solved it could be useful to verify the jwt manually in other use cases

  • default discord avatar
    gfwgfwlast year

    maybe this, packages/payload/src/auth/. Payload JWT is HS256, you can even write your own utils use jose or jsonwebtoken.


    somthing like:


    function isValidToken(token: string): boolean {
      // Implement your token validation logic here
      // This is just a placeholder example
      const hash = crypto
        .createHash('sha256')
        .update(process.env.PAYLOAD_SECRET || '')
        .digest('hex')
        .slice(0, 32)
      try {
        const decoded = jwt.verify(token, hash, { algorithms: ['HS256'] })
        return true
      } catch {
        return false
      }
    }
  • default discord avatar
    zenwhiskersmeowlast year

    thank you!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.