Vinzouz
Vinzouz

Reputation: 41

Session cookie not set in production with next-auth in Next.js

Using next-auth for my web application I have a problem with the session cookie only in production and being hosted. In local dev or production environments I have no problem. The callback-url and csrf-token cookies are present and so is session-token once connected.

My problem is when I host my application (on cPanel and on a subdomain), I have the secure callback-url and csrf-token cookies but when I try to connect I get no error and the session cookie doesn't initialize.

I've tried a lot of things but nothing works, if any kind soul has time for me, thank you !

Here's some code to reproduce the error :

The versions of next and next-auth I'm using in this project

    "next": "12.1.6",
    "next-auth": "^4.22.1",

The signIn function call for my login form

const result = await signIn('credentials', {
            username: usernameRef.current.value,
            password: passwordRef.current.value,
            redirect: false,
});

My [...nextauth].js file

const options = {
    providers: [
        CredentialsProvider({
            async authorize(credentials, req) {

                const { username, password } = credentials;

                const response = await fetch(`${req.body.callbackUrl}api/auths`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        username,
                        password,
                    }),
                })
                if (response.status === 200) {
                    const user = await response.json();
                    return user
                } else {
                    const message = await response.json();
                    throw new Error(message);
                }
            },
        }),
    ],
    session: {
        strategy: "jwt",
        maxAge: 15 * 24 * 60 * 60,
    },
    secret: process.env.NEXTAUTH_SECRET,
    callbacks: {
        async jwt(params) {
            const token = params.token;
            const user = params.user;
            if (user) {
                 ...
            }
            return token;
        },
        async session(params) {
            ...
            return params.session;
        },
    },
};

My auths API file is working properly My NEXTAUTH_SECRET environment variable is set to 32 characters and NEXTAUTH_URL is also of type https://mysubdomain.mydomain.fr

I tried to add this to my [...nextauth].js file with domain and without but without success.

cookies: {
  sessionToken: {
    name: `__Secure-next-auth.session-token`,
    options: {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      secure: true,
      domain: '.mysubdomain.fr'
    }
  },

Upvotes: 4

Views: 6273

Answers (1)

samuraiflo
samuraiflo

Reputation: 59

Hoping that this will help your implementation. I found your question while trying to find an answer to my own and figured I'd post the answer here in case it helped you. For a bit of context, my cookies weren't being set in any env if I tried to add the custom options (like httpOnly or secure).

I came across this discussion comment and a variation on the implementation for the next.config.js they provided was what finally worked for me:

const headers = [
  "Accept", "Accept-Version", "Content-Length",
  "Content-MD5", "Content-Type", "Date", "X-Api-Version",
  "X-CSRF-Token", "X-Requested-With",
];

module.exports = {
  reactStrictMode: true,
  async headers() {
    return [
      {
        source: "/api/(.*)",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          {  key: 'Access-Control-Allow-Origin', value: `${process.env.NEXT_PUBLIC_NEXTAUTH_URL}` },
          { key: "Access-Control-Allow-Methods", value: "GET,POST" },
          { key: "Access-Control-Allow-Headers", value: headers.join(", ") }
          ]
      }
    ];
  }
};`

Changing the origin to NEXT_PUBLIC_NEXTAUTH_URL is the only real change I made from the original comment. Hopefully this helps, it's the only thing I could find that got custom cookies working for me.

Also, in case it's helpful, the versions I'm using are:

"next": "^14.0.3"
"next-auth": "^4.24.5"

Upvotes: 1

Related Questions