Facebook Pixel

Where should I put public routes vs protected routes?

Put public routes (signup, login) outside any auth middleware. Then call router.use(auth) and put protected routes below. This keeps the structure clear and prevents accidental auth on public endpoints.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Express Route Protection With Middlewares

Write an auth middleware that verifies the JWT and sets req.user. Apply it to single routes, to a router (router.use(auth)), or in app.js. Keep public routes outside the auth middleware.

Read from req.cookies.token or req.headers.authorization (Bearer token). Verify with jwt.verify(token, process.env.JWT_SECRET). If valid, set req.user and call next; if not, return 401.

Add a second middleware after auth that checks req.user.role. If not allowed, return 403. Apply with router.use('/admin', auth, requireAdmin). Stack middlewares for layered auth.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.