0

I have a rails API running in the same cluster as my Next.js13 server. The rails API uses auth cookies to track the session.

I can log into a client side component and start making authenticated API calls based on the set-cookie header I receive from the rails API, however, when using an SSR component e.g....

export default async function MeTestPage () {
    try {
        let allCookies = cookies().getAll().map(c => `${c.name}=${c.value}`).join("; ");
        console.log(allCookies);

        let result = await fetch("http://0.0.0.0:3000/users/me", {
            "headers": {
                "accept": "*/*",
                "accept-language": "en-US,en;q=0.9",
                "sec-ch-ua": "\"Google Chrome\";v=\"107\", \"Chromium\";v=\"107\", \"Not=A?Brand\";v=\"24\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"macOS\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin",
                "cookie": allCookies
            },
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": null,
            "method": "GET",
            "mode": "cors",
            "credentials": "include"
        });
        let resultJson = await result.json();
        return <p>{JSON.stringify(resultJson)}</p>
    } catch (e: any) {
        return <p>{e.toString()}</p>
    }

The request goes through, rails gets the right cookies, but rails doesn't connect it to the session, I suspect because it's coming from a different IP address, though I haven't been able to figure this out.

I feel like one good solution would be to just proxy all client-side requests through the next server so that the next server can just act as the sole API client for rails and keep the IP consistent, but I'm not actually sure what the best way to do that is. I've tried both setting rewrites in next.config.js and also just copying the request method/route/headers/body to a new request from an /api/[...path].ts defined endpoint (but had a very frustrating time debugging why this wasn't sending the body).

I'm just getting into next.js and can't believe this is such a struggle-- I figure there must be some canonical way of handling this very common need to access a cookies protected API from both environments.

pixelpax
  • 1,435
  • 13
  • 22

0 Answers0