SalesforceCommerceCloud / pwa-kit

React-based JavaScript frontend framework to create a progressive web app (PWA) storefront for Salesforce B2C Commerce.
https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/pwa-kit-overview.html
BSD 3-Clause "New" or "Revised" License
278 stars 130 forks source link

[FEATURE] Normalize `request.ip` and `request.ips` on MRT #1667

Open johnboxall opened 7 months ago

johnboxall commented 7 months ago

In Express.js, you can you the Request object's properties req.ip and req.ips to access information about the IP address used to make a request:

https://expressjs.com/en/api.html#req.ip https://expressjs.com/en/api.html#req.ips

During local development, these properties return the correct IP, but when deployed to MRT, they no longer work as the true client IP is now contained in the x-forwarded-for header.

You can convince Express to trust the x-forwarded-for header and use its value by enabling the trust proxy setting:

app.set('trust proxy', true);

When we detect that the app is running in MRT, we should set this setting!

Screenshot 2024-02-13 at 3 26 15 PM

https://expressjs.com/en/4x/api.html#app.settings.table

johnboxall commented 3 months ago

In the context of ssr.js, if you need to pull the client IP out of you'll need to grab it from the HTTP request header x-forwarded-for when the app is deployed to MRT:

// ssr.js
app.get('/ip', function handleIp(req, res) {
    const ip = (req.get('x-forwarded-for') || '').split(',')[0] || req.ip
    return res.json({ip})
})

If you need the IP in SCAPI, you can send it using a Custom Query Parameter or Custom Header:

https://developer.salesforce.com/docs/commerce/commerce-api/guide/extensibility_via_hooks.html#conditional-behaviour