Search code examples
node.jsexpressgetroutesfetch

how to prevent from others to fetch my website url


I have a route in express app like this:

router.get('/search_documents_for_home_page', async (req, res) => {
  var responses = [];
  await Article.find({}).select('image title body').limit(4).sort({ _id:-1 }).then(articles=>{
    responses.push([articles]);
  });
  await Image.find({}).limit(4).sort({ _id:-1 }).then(images=>{
    responses.push([images]);
  });
  await Video.find({}).limit(4).sort({ _id:-1 }).then(videos=>{
    responses.push([videos]);
  });
  await Project.find({}).limit(4).sort({ _id:-1 }).then(projects=>{
    responses.push([projects]);
  });
  res.json(responses);
});

And when the user goes to the home page, a fetch request is sended:

await fetch('/api/search_documents_for_home_page').then(result=>{
    return result.json();
}).then(articles=>{
  // show the users all of the documents
});

But I want that only my server can fetch this url.

How do I do that?

Im also using pugjs


Solution

    1. You can secure your api by requiring some type of authentication
    2. You can add a check to make sure request is coming from your front end, depending on server this can be handled differently (i.e. window.location.origin)
    3. Enable CORS, only prevents browser>browser calls