Creating Authenticated APIs

We need to create new, user-specific APIs, and we want them to use our authed() middleware. But we certainly don’t want all the other routes (like our static file serving) to be authenticated. Those still need to be served without any authentication. So we can’t just call app.use() like we would with other middleware.

When you specify a route in Express, you can include middleware that you wish to apply to only that route. We’ll use this feature for the /api/user route:

web-app/b4/server.js
​ 
app.get(​'/api/user'​, authed, ​function​(req, res){
​ 
res.json(req.user);
​ 
});

This short route handler is all we need, thanks to the authed() function we already made. By the time the route handler is invoked, ...

Get Node.js the Right Way now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.