Search code examples
ruby-on-railsreactjsfetchnext.js

Server's location is being sent instead of user's location


I have the following stack:

  • Rails API (backend)
  • Next.js (frontend)

In my Rails API, I am tracking where the request is coming from such as ip, user_agent, city, country, latitude, and longitude.

But the problem is that, instead of the user's data, it's the server's data that is being sent.

In my Next.js app, I use https://nextjs.org/docs/api-routes/introduction, since the access_token for the API is stored in the session. And I don't want to expose it to the client.

So the process would be, from React, I will make a POST request to /api/process/ of Next.js API endpoint. Then in /api/process I will take the access_token from the session and make a request to Rails API.

Since the Next.js API endpoint is the one made the request to Rails API. My Rails API stores the location of the frontend server instead of the actual user's info.

Pseudocode:

In React Frontend:

fetch('/api/process', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ some: 'data' })
})

In pages/api/process.js:

export default function handler(req, res) {
  fetch(RAILS_API_ENDPOINT, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: `Bearer ${req.session.token}` // attach token here
    },
    body: req.body
  })
}

Is there any workaround for this? I don't seem to want to expose the access_token in the client and make the request there to the Rails API directly.


Solution

  • You've set up a proxy API, as a result the Rails server knows nothing about the FE client because theres a layer in between. So there are 2 options:

    1. Set up the FE client to call rails directly (which you said you don't want to do).
    2. Forward this FE client information as part of either headers or in the payload to the rails API. From there the Rails API can then do whatever it wants with this data.