Search code examples
node.jsexpressjestjsjwtsupertest

Why are Express post responses duplicated?


I have a simple express application with one post route that returns a JSON web token.

const express = require('express')
const { sign } = require('jsonwebtoken')

const app = express()

app.post('/jwt', (_, response) => {
  const payload = { data: { email: 'example@example.com' } }
  const jwt = sign(payload, 'secret')

  response.json({ jwt })
})

module.exports = app

It is expected that every time a POST /jwt request is made, a unique token would be returned. I also have a test that makes two requests to the server and expects both to succeed and return different tokens.

const request = require('supertest')
const app = require('./app')

it('should return different tokens', async () => {
  const first = await request(app).post('/jwt').expect(200)
  const second = await request(app).post('/jwt').expect(200)

  expect(first.body).not.toEqual(second.body)
})

This is mostly true when the requests are executed at certain intervals, but in cases where the requests are executed simultaneously, then the responses are duplicated and the test fails. Is there a way to fix this without introducing artificial timeouts and ensure that my test passes every time?


Solution

  • There's nothing in your code that makes the JWT tokens unique. You are 100% depending on the iat timestamp for this uniqueness therefore it makes perfect sense that two tokens generated at the exact same millisecond would be identical.

    If you want the tokens to be unique add something unique to the payload:

    app.post('/jwt', (_, response) => {
      const payload = {
        data: { email: 'example@example.com' },
        unique: Math.floor(Math.random()*999999999999999).toString(16)
      }
      const jwt = sign(payload, 'secret')
    
      response.json({ jwt })
    })
    

    Obviously you can use some GUID or UUID or session module to generate this unique data and you can name it anything you like such as sessionID or uuid etc. but the above is a simple example of what you need to do to guarantee uniqueness.