How to get API call origin in NextJS API endpoint

1.6k Views Asked by At

I have an API set up that receives a token, and I want to store that token in a database. But I also want to store the origin URL.

Let's say my API endpoint is located at https://myapp.com/api/connect

Now, I want to send a token from my website https://mywebsite.net

After I send a token, I want to be able to store the token and the website URL to the database in NextJS code.

My endpoint would store this info to the database:

{
  token: someRandomToken
  origin: https://mywebsite.net
}

I tried logging the whole req object from the handler to see if that info exist but the console log fills my terminal fast.

1

There are 1 best solutions below

0
On BEST ANSWER

Inside Next's Server-Side environment you have access to req.headers.host as well as other headers set by Vercel's or other platforms' Reverse Proxies to tell the actual origin of the request, like this:

/pages/api/some-api-route.ts:


import { NextApiRequest } from "next";

const LOCAL_HOST_ADDRESS = "localhost:3000";

export default async function handler(req: NextApiRequest) {
  let host = req.headers?.host || LOCAL_HOST_ADDRESS;
  let protocol = /^localhost(:\d+)?$/.test(host) ? "http:" : "https:";

  // If server sits behind reverse proxy/load balancer, get the "actual" host ...
  if (
    req.headers["x-forwarded-host"] &&
    typeof req.headers["x-forwarded-host"] === "string"
  ) {
    host = req.headers["x-forwarded-host"];
  }

  // ... and protocol:
  if (
    req.headers["x-forwarded-proto"] &&
    typeof req.headers["x-forwarded-proto"] === "string"
  ) {
    protocol = `${req.headers["x-forwarded-proto"]}:`;
  }

  let someRandomToken;
  const yourTokenPayload = {
    token: someRandomToken,
    origin: protocol + "//" + host, // e.g. http://localhost:3000 or https://mywebsite.net
  };

  // [...]
}

Using Typescript is really helpful when digging for properties as in this case. I couldn't tell if you are using Typescript, but in case you don't, you'll have to remove NextApiRequest.