This is drafted post. Please setdraft: falsein this .mdx file once ready to be published.

Implement JWT in WebSocket in Just 2 Steps

3 Min Read

Vyom Srivastava

In past articles, we have covered the high level and essential ideas of WebSocket. So in this article, we'll be covering how to utilize JWT tokens in WebSockets.

The WebSocket library I decided to utilize is ws. Also, my arrangement is straightforward.

  • Gain a token from the worker
  • Send that token as an extra header

On the worker side, get the header, in the event that substantial, at that point alright however on the off chance that not, at that point bomb the association

Furthermore, I became acquainted with this cool thing called JWT. In one line, it is a splendid method of having stateless verification.

Outfitted with all the amazing libraries and articles the Node.js people group gives, I wound up really executing the arrangement.

JWT module for hub gives all the vital capacities and the ones applicable to my situation were a sign and confirm.

Step -1: Generating a Token using JWT

Now we have to install one more package that is jsonwebtoken by using below command:

npm i jsonwebtoken

To sign an item I need a mystery key and the item to sign. I can likewise give extra choices, for example, after how long the JWT token will lapse. So create a file client.js and paste the below code:

var jwt = require('jsonwebtoken')
var token = jwt.sign({name:'firecamp'},'YOUR_SECRET_KEY_HERE',{
expiresIn : 15 * 24 * 60 * 60 * 1000 // 15 days

Code Explanation:

We’re importing the jsonwebtoken package that will generate a new token every time you execute this code. We have defined an expiry date of to be 15 days, you can pick any time you want. You also have to pass a secret key here which is used to generate a unique token. So make sure you keep it in a safe place. I would advise you to store the secret key in the environment variable so it won’t get exposed anywhere.

Step -2: Setting up the server

Presently on the client side, I should have a token. Suppose I got it from the worker. Next is to set up a WebSocket association and send this obtained token in headers' segment.

What's more, this is the way we do it (I think) utilizing the ws module. While introducing, we pass a [options] object, which contains the token, and indicates that it should be added to the headers.

The worker land follows a similar example as in the customer land. While instating, we pass a [options] object, which has a capacity under the property field verifyClient.

verifyClient is furnished with two contentions:

info Object:

  • source String: The incentive in the Origin header showed by the customer.

  • req http.ClientRequest: The customer HTTP GET demand.

  • secure Boolean: valid if req.connection.authorized or req.connection.encrypted is set.

cb Function: A callback that should be called by the endless supply of the data fields. Contentions in this callback are:

  • result Boolean: Whether the client acknowledges or not the handshake.
  • code Number: If result is bogus this field decides the HTTP mistake status code to be shipped off the customer.
  • name String: If result is bogus this field decides the HTTP reason express.

Now create a file server.js and paste the below code:

const wss = new WebSocketServer({
port : 8080
wss.on('connection', ws => {
function verifyClient(info, cb) {
var token = info.req.headers.token
if (!token)
cb(false, 401, 'Unauthorized')
else {
jwt.verify(token, 'secret-key', function (err, decoded) {
if (err) {
cb(false, 401, 'Unauthorized')
} else {
info.req.user = decoded //[1]

Code Explanation:

We’re importing ws package and we have defined different conditions here. The function verifyClient is used to verify the token. So if the header with a token isn’t passed then it’ll just disconnect the connection, if the token is wrong then it’ll pass the Unauthorized error.

Step -3: Testing the Token

Now to generate a token paste the below code in your terminal and copy the token from there:

node client.js

Once done, you can now run the server by using the below command:

node server.js

Once it’s up, open the FireCamp application and select WebSocket from the menu. The WebSocket server is running on URL: ws://localhost:8080 and now in the Headers pass you token, you’ll have something like this:


That’s all folks!! You have successfully implemented the JWT in WebSockets.

Final Words

You have now implemented the JWT authentication in WebSockets, this authentication is one of the most secure methods. You can do other authentication as well like Basic auth. If you have any confusion you can comment down below, we’ll resolve it as soon as possible.

Step -1: Generating a Token using JWTStep -2: Setting up the serverCode Explanation:Step -3: Testing the TokenFinal Words


DownloadDocChange LogsCookiesTerms & ConditionsPrivacy PolicyContact Us

Apps & Integrations


Firecamp Newsletter