File size: 789 Bytes
6215321
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { createSecretKey } from "crypto"
import { SignJWT } from "jose"

// https://jmswrnr.com/blog/protecting-next-js-api-routes-query-parameters

export async function getToken(data: Record<string, any> = {}): Promise<string> {
  const secretKey = createSecretKey(`${process.env.API_SECRET_JWT_KEY || ""}`, 'utf-8');

  const jwtToken = await new SignJWT(data)
   .setProtectedHeader({
    alg: 'HS256'
   }) // algorithm
   .setIssuedAt()
   .setIssuer(`${process.env.API_SECRET_JWT_ISSUER || ""}`) // issuer
   .setAudience(`${process.env.API_SECRET_JWT_AUDIENCE || ""}`) // audience
   .setExpirationTime("1 day") // token expiration time - to prevent hackers from re-using our URLs more than a day
   .sign(secretKey); // secretKey generated from previous step

  return jwtToken
}