With next.js, how can I restrict requests to API routes to only come from the web page?

Viewed 2790

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

2 Answers

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.

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.

Related