Reputation: 3639
I'm creating an express project and I have some routes to provide data to frontend controllers via ajax, for instance they begin with /get_data
.
So my question is how to protect these routes? Anyone can access them easily. I tried to do
app.use((req, res, next) => {
if(!req.xhr) res.sendStatus(404);
else next();
})
But this doesn't prevent ajax calls from other sites to access the data. So how to make it more secure? If it's not possible, in what way can I provide data to frontend?
Upvotes: 0
Views: 1508
Reputation: 275
One option is using CORS (there is an express middleware). So you can configure your route to accept requests from the specific origin only. But the origin can be faked.
If you have some sensitive data there, you may consider adding Authentication (and maybe Authorization) to your application. There are a lot of ways of implementing that, for example popular Passport.js library.
Also there are some details in answers to How to implement a secure REST API with node.js Ask Question.
Upvotes: 2