6

I have API routes that I want to restrict to only allow from the web (react) application. Can this be achieved?

Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • 1
    You can try configuring CORS settings. Although other frontends (on not very old browsers) won't be able to send a request, but any backend will be (also if one just opens the endpoint on browser directly). If you want to prevent that also, then you may need to configure your API endpoints to use some authentication system like JWT. – brc-dd Jun 17 '21 at 14:39
  • 2
    Does this answer your question? [How to prevent arbitrary client apps from using anonymous web API?](https://stackoverflow.com/questions/5333368/how-to-prevent-arbitrary-client-apps-from-using-anonymous-web-api) – Quentin Jun 18 '21 at 12:36

2 Answers2

4

Check out the official docs.

The following is the options you'd pass to the cors middleware:

const corsOptions = {
  origin: 'http://domain-of-your-webapp.com',
}

Edit:

As brc-dd and you pointed out, above solution won't protect from anything other than a browser trying to access your API.

I went over this thread, and it seems that the conclusion is it's extremely not worth the effort if you want your API to be anonymous.

If you do settle for authentication then NextAuth.js is a simple and quick solution for Next.js applications.

EcksDy
  • 1,289
  • 9
  • 25
  • 1
    This is for CORS. But the API can still be hit via cURL, etc. I want to disable all origins that are not the specified one. – Shamoon Jun 17 '21 at 19:27
  • Unfortunately I don't know a way to do that. Anyone can freely tamper with the Origin header with the right set of tools. I've edited the answer to suggest an alternative. – EcksDy Jun 18 '21 at 12:36
  • 1
    @Shamoon I wrote a simple code for this, give it a try: https://stackoverflow.com/a/68215621/11613622 People can still use cURL to get the data from it, but it will be harder for them as the access token is short-lived. – brc-dd Jul 01 '21 at 19:04
2

A posible solution to this is to use something like Recaptcha.

  1. Your website's frontend generates a verifing code, only from your domain. And it is verified by a third party like Google.
  2. Your backend verifies that the code is correct, what means it was generated from your url. (in recaptcha's case it also checks it is a human).

Hope it helps.

Daniel
  • 1,189
  • 2
  • 12
  • 30