This website collects cookies to deliver better user experience
How to protect NextJS API routes from other browsers/servers
How to protect NextJS API routes from other browsers/servers
So you have any API routes that you don't want anything to access other than the UI (main website) itself, and you don't want to keep writing if statements on every single one of your API routes. What's the solution?
Writing middleware
Let's create a folder called middleware in our NextJS project and under it create a file called protectAPI.js.
Now let's see what's going on here. First of course we define the function protectAPI. We return an asynchronous function which has our req and res.
Now we check the domain that's sending a request with req.headers.referer and seeing if it's not our domain name, return the 403 code and a Forbidden message.
Using this middleware
So we have an API file which is under /api/hello.js. How do we protect it?