'getSession next-auth returns null

I am learning NextAuth, and I am just trying to get my current session in an API. Looks pretty easy from the documentation, but it keeps giving me null. If I use useSession from the client-side, I do get the current session though. What am I doing wrong?

import { getSession } from 'next-auth/react';


const handler = nc().use(Cors());

handler.post(async (req, res) => {
    if (req.method === 'POST') {
        const session = await getSession({ req });
        if (session) {
            console.log('Session', JSON.stringify(session, null, 2));
        } else {
            console.log('Not authenticated.');
            res.status(401);
        }
        res.end();


Solution 1:[1]

Took me a lot of time to understand this issue. The solution could be one of the following:

If the next-auth server cannot access the canonical URL defined in the env var NEXTAUTH_URL (like https://example.com is not reachable from the nextjs server host), another env var must be defined as localhost (mapping to the nextJS server host or docker container): NEXTAUTH_URL_INTERNAL=http://localhost:<your nextJS host port>.


Check: https://next-auth.js.org/v3/configuration/options#nextauth_url_internal. This var will set next-auth server side actions to execute localhost (it makes sense, since getServerSideProps() from nextJS calling getSession() for example will invoke a localhost action, doesn't need to route outside)

If setting the internal var doesn't solve, could be due to secure cookies (HTTPS). In authoptions{} set useSecureCookies: false,: this will tell next-auth to never set the cookies as secure site only (HTTPS)

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 juliomalves