Next.js Discord

Discord Forum

Setting cookies() httpOnly aren't set in localhost

Answered
Asiatic Lion posted this in #help-forum
Open in Discord
Avatar
Asiatic LionOP
Hello everyone,

Why is that in localhost, the cookies aren't set, when I add the httpOnly attribute to the setter function like in the example in the official docs?

cookiestore.set({
name: 'userSessionID',
value: nanoid(24),
httpOnly: true,
path: '/'});


But when I only use this way:
cookiestore.set('userSessionID',nanoid(24));


it gets set.
Answered by Ray
ok could you update the code to this and try again?
"use server";

import { loginType } from "@/lib/loginType";
import { redirect } from "next/navigation";
import { cookies } from 'next/headers';
import { nanoid } from "nanoid";
import bcrytp from 'bcrypt'
import { isRedirectError } from "next/dist/client/components/redirect";

export default async function userLoginDB(login: loginType): Promise<void> {
  try {
    const cookieStore = cookies();

    const passwordHash = await bcrypt.hash(login.password, 8);
    const matched = await bcrypt.compare(login.password, passwordHash);

    if (!matched) redirect("/signin");
    
     console.log(matched);
     cookieStore.set("userSessionID", nanoid(24), { httpOnly: true });
    
  } catch (error) {
    if (isRedirectError(error)) throw error
    redirect("/signin");
  }
}
View full answer

24 Replies

Avatar
Ray
where do you set the cookie? route handler or server action?
Avatar
Asiatic LionOP
I am using a seeparate file with 'use server' directive
But now it doens't even want to set the cookie at all, no matter what I rewrite in vscode
Avatar
Ray
could you show the code? and the code on where you call it
Avatar
Asiatic LionOP
moment please
'use server'

import { loginType } from '@/lib/loginType';
import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import { nanoid } from 'nanoid';

const bcrypt = require('bcrypt');

export default async function userLoginDB(login:loginType): Promise<void> {

    const cookieStore = cookies();

    const logger = () => {
        bcrypt.hash(login.password, 8, async function (err:string, hash:string) {
            bcrypt.compare(login.password, hash, async function (err: string, result: boolean) {
                try {
                    if (result) {
                        console.log(result);
                        cookieStore.set('userSessionID', nanoid(24));
                    }
                }
                catch (err) {
                    return redirect('/signin')
                }
            })
        })
    };

    logger();
}
the bcrypt.compare works fine, only the cookies.set() isnt
Avatar
Ray
why are you hashing the password and compare it?
it will always match
Avatar
Asiatic LionOP
yes, and it works ok as far as I know
but the if checks if it is TRUE right?
in the try catch
or am i understanding Javascript wrong?
Avatar
Ray
ok could you update the code to this and try again?
"use server";

import { loginType } from "@/lib/loginType";
import { redirect } from "next/navigation";
import { cookies } from 'next/headers';
import { nanoid } from "nanoid";
import bcrytp from 'bcrypt'
import { isRedirectError } from "next/dist/client/components/redirect";

export default async function userLoginDB(login: loginType): Promise<void> {
  try {
    const cookieStore = cookies();

    const passwordHash = await bcrypt.hash(login.password, 8);
    const matched = await bcrypt.compare(login.password, passwordHash);

    if (!matched) redirect("/signin");
    
     console.log(matched);
     cookieStore.set("userSessionID", nanoid(24), { httpOnly: true });
    
  } catch (error) {
    if (isRedirectError(error)) throw error
    redirect("/signin");
  }
}
Answer
Avatar
Asiatic LionOP
the console.log(matched) returns true but no cookie showing up, I'll try restarting the browser
Avatar
Ray
check the network tab on your dev tools
and see if there is a Set-Cookie header from the response
Avatar
Asiatic LionOP
ok, my mistake, i shouldn't have added in another async functiona nd call that inside the useLoginDB async function
it works now
there was that logger function inside the userLoginDB functiona nd that might have been the issue
so, it's ok now, thank you so much for hellping me out 🙂
Avatar
Ray
np, bcrypt return promise, so you can use async/await with it
Avatar
Asiatic LionOP
i see, will do 😉