To obtain the client's IP address in ElysiaJS, you can use the request.ip property within the request object. ElysiaJS is built on top of Node.js, so the method to retrieve the IP address is similar to that in Express or Koa.
Here is a specific example demonstrating how to set up a simple server in ElysiaJS and print the request IP address for each request:
javascriptconst Elysia = require('elysia'); const app = new Elysia(); app.use((ctx, next) => { console.log(`Request IP: ${ctx.request.ip}`); next(); }); app.get('/', (ctx) => { ctx.response.send('Hello World'); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
In this example, we first import the Elysia module and then create an instance of Elysia. We use middleware (via app.use) to capture each incoming request and retrieve the request IP address using ctx.request.ip, printing it out. Then, we define a simple route handler that returns 'Hello World' when users access the root directory ('/').
This approach works for most basic cases. However, if your server is behind a proxy, such as Nginx, you might receive the proxy's IP address instead of the client's real IP address. In this case, you may need to use HTTP headers like X-Forwarded-For to retrieve the original IP address. This can be achieved by modifying the middleware code, as shown below:
javascriptapp.use((ctx, next) => { const xForwardedFor = ctx.request.headers['x-forwarded-for']; const ip = xForwardedFor ? xForwardedFor.split(',')[0] : ctx.request.ip; console.log(`Request IP: ${ip}`); next(); });
Here, we first attempt to retrieve the IP address from the x-forwarded-for header. If it exists, we take the first IP address (since x-forwarded-for may contain multiple IP addresses added by each node in the proxy chain). If the header does not exist, we fall back to using ctx.request.ip.
With this method, even when the application is deployed behind a proxy server, we can correctly retrieve the original request IP address.