javascriptnext.jsjwt

JWT authentication in a Next.js API with the Edge Runtime. JWTClaimValidationFailed: "nbf" claim timestamp check failed


Problem: JWT Claim Validation Error (nbf)

Recently, I encountered a problem while using JWT authentication in a Next.js API with the Edge Runtime. The error message was:

JWTClaimValidationFailed: "nbf" claim timestamp check failed


Solution

  • This error occurs because the JWT (JSON Web Token) has an nbf (Not Before) claim, which specifies the earliest time at which the JWT is valid. The issue is caused by slight time differences between the client and the Edge Runtime server, making the nbf value invalid.

    Why This Happens

    Solution: Use Clock Tolerance in JWT Verification

    To solve this problem, I added a clockTolerance option in the JWT verification process, which provides a small window of time to account for clock drift.

    Updated Example JWT Verification Code

    // src/pages/api/auth/verify.js
    import * as jose from 'jose'
    
    const jwtConfig = {
      secret: new TextEncoder().encode(process.env.BACKEND_JWT_SECRET)
    }
    
    export default async function handler(req, res) {
      if (req.method !== 'POST') {
        return res.status(405).json({ error: 'Method not allowed' })
      }
    
      try {
        let token = req.headers.authorization
    
        if (!token) {
          return res.status(401).json({ isAuthenticated: false, error: 'No token provided' })
        }
    
        if (token.startsWith('Bearer ')) {
          token = token.replace('Bearer ', '')
        }
    
        const decoded = await jose.jwtVerify(token, jwtConfig.secret, {
          clockTolerance: '5s' // Allows a 5-second tolerance for clock drift
        })
    
        if (decoded.payload) {
          return res.status(200).json({ isAuthenticated: true, user: decoded.payload })
        }
      } catch (err) {
        console.error('Token verification error:', err)
        return res.status(401).json({ isAuthenticated: false, error: 'Invalid token' })
      }
    }
    

    Why This Works

    Conclusion

    If you are using JWT authentication in a distributed system or Edge Runtime environment, always consider using clockTolerance to avoid time synchronization issues.