Search code examples
node.jsexpressjwtexpress-jwt

Secure only some routes with express-jwt


I have "public" routes, and "API" routes which should be authenticated by express-jwt.

// define public routes in a router
const routerPublic = express.Router();
routerPublic.route("/login", (req, res) => /* whatever */);
routerPublic.route("/about-us", (req, res) => /* whatever */);
routerPublic.route("/foo/bar/baz", (req, res) => /* whatever */);

// define API routes in a router
const routerApi = express.Router();
routerApi.route("/api/v1/foo", (req, res) => /* whatever */);
routerApi.route("/api/v1/bar", (req, res) => /* whatever */);

// add routers to express app
app.use(routerPublic);                                 // (1)
app.use(routerApi, jwt({ secret: "secret" }));         // (2)

So I populate two express.Router instances - one with unsecured routes, and the other with secured routes. Then I load those routers into the express app, and only the secured routes should undergo authentication.

But the order is important. If line (1) comes before (2) then it works as expected. But if (2) comes before (1) then everything undergoes authentication, both secure and insecure routes.

So there is a race condition and I don't understand it.


Solution

  • Posting it as an answer in order to help others,

    Your using the new express route, can you try something like this:

    routerApi.use(jwt({ secret: "secret" }))