How can i check a JWT token is valid using an async function route with nodejs?

Issue

I am following the guide below to verify that only registered users can send requests to my backend nodejs server, my frontend is sending requests with an authorization header that contains a token and that part is working well. The nodejs backend should then check the token is valid before sending a response:
https://www.tonyvu.co/posts/jwt-authentication-node-js

The example shows i should add ‘AuthenticateJWT’ like the following to my route:

app.post(“/api/token”, authenticateJWT, (req, res) => {
...
});

However my route is an async function and i can’t find the correct syntax to add it. My code is the following:

router.post('/account/user_load_balance',  async function (req, res) {

 ...  
});

I have tried the following:

router.post('/account/user_load_balance',  async function, authenticateJWT (req, res)     try {
 ...
});

but this gives me an error:

Unexpected token ','

what is the correct syntax?

Solution

You can turn the example code:

app.post(“/api/token”, authenticateJWT, (req, res) => {
    ...
});

into an async function example, simply by adding the async keyword to the function that already exists:

app.post(“/api/token”, authenticateJWT, async (req, res) => {
    ...
});

It should be trivial to adapt this to your own use, assuming that you have an authenticateJWT that’s already functional.

See also:

Answered By – Doug Stevenson

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published