Nuxt3 server middleware: client ip is undefined

282 views Asked by At

I have a middleware under server/middleware/auth.ts and am trying to gate some of my REST endpoints so they can only come from localhost (for the case where an internal tool communicates back to the webserver). For some reason though all the various options I tried all return undefined.

To get any of the fields below populated, is there some setting I'm missing?

export default defineEventHandler((event) => {
    const ipAddress = getRequestIP(event) ||
                      event.node.req.socket.remoteAddress ||
                      'unknown'
    // ipAddress is always 'unknown' here.
}
1

There are 1 answers

4
Ellrohir On

In our project we read IP from event.node.req.headers['x-forwarded-for']. Since it can hold more than one value, it has to be parsed. This is our util method:

function getIp (req: IncomingMessage) {
  const ipHeader = req.headers['x-forwarded-for'] as string
  return ipHeader ? ipHeader.split(/, /)[0] : req.socket.remoteAddress
}

There is remoteAddress as a fallback, but it is possible, there is nothing, like it is happening to you...