Diego Ulloa
Diego Ulloa

Reputation: 639

Nextjs: API route accessible only from the server (SSR)

I have an api route /get-data which by default is open to public.

I want to return data from this endpoint (data I get from a paid external service) only if the server itself (SSR page) is requesting the data.

This is to prevent the external service abuse, where I have only 2000 request per month.

Is there any way to do it? Maybe detecting in the api req object if the request is coming from the same server or from a browser...

Probably is impossible to make the /get-data route private, but for sure I can return an empty data object, an error or something if the request is not coming from the server.

Upvotes: 0

Views: 4016

Answers (1)

illia chill
illia chill

Reputation: 2056

To begin: You have page > your API /get-data > external API

You make all your requests logic in your API /get-data and not on the page.

What you can do in your /get-data API:

A. You can secure your API route.

  • You have a lot of tools and services such as Auth0 SDK to secure your pages and API routes according to your roles or permissions

  • You can set up a password, stored in .env file, generated by you. For example:

    //inside SSR page
    await fetch(`your_base_path/api/get-data?password=your_password`)
    
    //your api code
    if (process.env.password == req.query.password){
      //your code with accessing external API
      //I recommend you to save all incoming request to track where and when requests are coming.
    }
    else{
     //you can return your empty object here
     res.status(401)
    }
    

B. You can check your current limit of monthly requests by saving each request in your DB and checking the number of requests before contacting an external API.

C. You can track the IPs of requests with this library and save them. (For example to block after you see someone is making a lot of requests you don't like)

D: (advanced) you can develop your logic to generate access tokens for your API route. For example, you can create API route /generate-token and generate token based on your parameters.

Example:

Every time your SSR page triggered, your code

  • generates the token based on your parameters (route, time, user etc.) by sending data from the page to /generate-token

  • once token is generated you call your await fetch(your_base_path/api/get-data?password=your_token_generated) on your page, with your recently generated token.

  • you validate your token in /get-data

Notice: don't give access by IP, because IP of your server may differ (for example, in vercel) so the IP address is not a robust validation parameter.

P.S. You can develop your logic for your question, but the most important thing is to develop your logic in /get-data and not on the page. Also, once you have defined your .env variable, don't forget to add your env variable to your server.

Upvotes: 2

Related Questions