Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS Route Async Middleware

I'm trying to use a middleware in Express but I can't get it to work I get infinite loading time when I make a request. I searched on stackoverflow but I couldn't find any examples that used an async await middleware stored in a separate file. Can someone point me in the right direction?

isAuthenticated.js

const Auth = require('../auth/auth')

const isAuthenticated = async () => {
    return async (request, response, next) => {
        const token = request.cookies.token;
        try {
            const JWTVerify = await Auth.verifyJWTToken(token);
            next()
        } catch (error) {
            response.json({ status: "failed", message: "Authentication failed invalid token" });
            response.end();
        }
    }
}

module.exports = isAuthenticated

Server.js

const isAuthenticated = require('./middleware/isAuthenticated')

app.post('/some-route', isAuthenticated, async (request, response) => {


});

like image 977
Josh Avatar asked Nov 24 '25 07:11

Josh


1 Answers

You returning a function, and thus the middleware is not passing the request forward.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

check ---> http://expressjs.com/en/guide/writing-middleware.html

const Auth = require('../auth/auth')

const isAuthenticated = async  (request, response, next) => {
        const token = request.cookies.token;
        try {
            const JWTVerify = await Auth.verifyJWTToken(token);
            next()
        } catch (error) {
            response.json({ status: "failed", message: "Authentication failed invalid token" });
            response.end();
        }
    }


module.exports = isAuthenticated
like image 200
Samuel Momanyi Avatar answered Nov 26 '25 23:11

Samuel Momanyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!