0

I am building a Next.js application in which I want to restrict access to my APIs. I only want my application to make those requests.

I once built an app with MERN stack, and I remember I used cors to only allow my domain to make requests to my APIs. But apparantly cors does not work with nextJS, and I tried many npm modules such as nextjs-cors but they didn't work.

I am thinking about using firebase App Check in order to check if this is my app that is making the requests, but I am still hesitant.

What do you think is the optimal and professional solution for this?

P.S.: Is there a similar behavior to cors in but in NextJS because I also remember cors did not allow postman to make requests as well to my APIs.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197

1 Answers1

0

That is what API keys are for. Since you have control over both client and server, in client requests you can add a random key to headers when you make request. Then on the server, you can extract the headers console.log(req.headers), if the headers include the specific key and matching value, you process the request if not you reject the request.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • Where should I define the key? Should it change from time to time like tokens? And how to hide the key from the client side? –  Oct 01 '22 at 21:23
  • @DormatiTech it is not going to be like api key that is provided by the authentication servers. they use public/private key cryptography. in your case, you could just send any arbitrary string to the server, and server extracts it and compares it. You can store it as an env variable and everytime you make a request you attach it to the request headers – Yilmaz Oct 01 '22 at 21:27