React + Next : Not sending cookies from server-side to backend

Viewed 924

I am using kubernetes for backend(microservices) and react(client).

I am able to send / authenticate via cookies when the request is being sent from the browser(client side) but when the app first loads(server side), I am unable to authenticate.

Which means it is not sending requests from the server side.

Proof:

AppComponent.getInitialProps = async (appContext) => {
    let data = {};
    const client = apiRequest(appContext.ctx); // <== custom axios instance 
    console.log(`${appContext.ctx.req.headers}`); // <== This is showing null
    try {
        const res = await client.post('/api/users/currentuser'); // <== to check logged in user 
        data = res.data;
    catch (err) {
        if (err) data = { currentUser: null }
    }
    let pageProps = {};
    if (appContext.Component.getInitialProps) {
        pageProps = await appContext.Component.getInitialProps()
    }
    return { pageProps, ...data }
}

Custom axios function:

export const apiRequest = ({ req }) => {
    if (typeof window === undefined) {
        // we are on server side 
        return axios.create({
            baseURL: 'http://ingress-nginx-controller.ingress-nginx.svc.cluster.local',
            // to pass cookies and hostname needed by ingress while resolving the request coming
            headers: req.headers
        })
    }
    return axios.create({
        baseURL: "/"
    })
}
1 Answers

I'm (also?) doing an online course around this and ran into this same issue. The issue being that some calls to getInitialProps() don't always include the application context for some reason. Unfortunately, I don't have a direct answer for why that's failing. Regarding the missing cookies, you may be requiring that your cookies are only sent over secure https connections? For example, here's what I've got in my project:

app.use(
  cookieSession({
    name: "teekeet.com session",
    signed: false, // Disable cookie encryption to better support different service platforms (java, ruby, nodejs etc)
    secure: process.env.NODE_ENV !== "test", // Cookies should only be used over HTTPs
    maxAge: 1 * 10 * 60 * 1000, // 10mins
  })
);

In any case, assuming you're running version 9.3+ of NextJS then you should move to the newer APIs that provide explicit Server Side rendering hooks. Specifically the getServerSideProps() API. The NextJS docs provide a good explanation on how to use the new features. Check out their guide here. Also, feel free to poke around my project in github as a reference.

Related