'getSession from NextAuth returns null in api if the call comes from getServerSideProps

I have have an NextJS application that uses some proxy rewrite to add auth headers from session to request header. This works fine on pages that do not use SSR.

When i try to make a request via apollo client in getServerSideProps, then getSession is suddenly null in the api route.

api route code:

import { getSession } from 'next-auth/react';
import httpProxyMiddleware from 'next-http-proxy-middleware';
import readDockerSecret from 'Utils/secret';
const middleware = async (req: NextApiRequest, res: NextApiResponse) => {

    const session = await getSession({ req });
    const token = session?.access_token;
    if (!session) console.log('No session❤️‍🔥');
    if (session) console.log('Got session🥑');

    return httpProxyMiddleware(req, res, {
        target: readDockerSecret('NEXUS_GRAPHQL_REWRITE_URL') || process.env.NEXUS_GRAPHQL_REWRITE_URL,
        pathRewrite: {
            '^/api/graphql': ''
            // changeOrigin: true
            // proxyTimeout: 5000
            // secure: true
        },
        headers: { Authorization: `${token}` }
        // headers: { Authorization: `${token}` }
    });
};
export default middleware;```

Is there something i have to do to make sure i have a session when using ssr in nextjs (with nextauth)?


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source