Skip to content
Advertisement

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

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?

Advertisement

Answer

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:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement