Shamoon
Shamoon

Reputation: 43531

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

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

Upvotes: 7

Views: 12249

Answers (2)

Daniel
Daniel

Reputation: 1267

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.

Upvotes: 3

EcksDy
EcksDy

Reputation: 1654

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.

Upvotes: 4

Related Questions