Next.js Discord

Discord Forum

Setting Cookies within fetch-Block

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
Hello,

i've tried to a set a cookie within a .then()-Block of a fetch request. However the cookie seems to not appear inside the Browser's Developertools.

But when I try to console.log(cookies().getAll()); it shows my cookie.
How does that behaviour explain? And what can I do to get around it?

Greetings

18 Replies

Toyger
where do you set cookie?
where exactly in dev tools you are checking them
Sun bearOP
I'm setting it inside the 2nd .then-Block

fetch(URL {options}).then(async response => { [...] return await reponse.json() }).then(data => { cookies().set('Example', 'example', {options }) }).catch(error) {[....]}

I've tried to outsource the cookie into another function passing down the data e.g.:

.then(data => setCookie(data))

export const setCookie = async (data: any) => { cookies().set('Example', 'example', {options}); }

Same result, does not show up inside the browser.
I'm looking them up in Safari's Developer Tools in Storage > Cookies
Same in Google Chrome
Sun bearOP
Yeah, i've done that. But there is no cookie
@Sun bear Yeah, i've done that. But there is no cookie
Toyger
can you show your code
wait
export const login = async (formData: FormData) => {
    try {
        const credentials = {
            email: formData.get('email'),
            password: formData.get('password')
        };
            
        fetch('http://localhost:8080/auth/login', {
            method: 'POST', 
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(credentials)
        })
        .then(async response => {
            if (!response.ok) {
                throw new Error('Network response was not ok')
            }
            return await response.json()
        })
        .then(data => setCookie(data))
        .catch(error => {
            console.error('There was a problem with your fetch operation: ', error);
        });
    

    } catch (error) {
        console.log(error);
    }
}

export const setCookie = async (data: any) => {
    const expires = new Date(Date.now() + 300 * 60 * 1000);
    const session = await encrypt({data, expires});

    cookies().set('session', session, { expires: expires, httpOnly: true, });
    cookies().set('test', 'test', { expires: expires, httpOnly: true, })
};
How can I do a proper code-block in Discord ?
@Sun bear How can I do a proper code-block in Discord ?
Toyger
function s(){return 0;}


```js
```
@Toyger js function s(){return 0;} \`\`\`js \`\`\`
Sun bearOP
THanks
login is called within a form action
I've got it working perfectly beforehand. But once I used the fetch + .then Block it doesnt seem to work

I've done it like

  export const login = async (formData: FormData) => {
    const response = await fetch(URL);
    const dataJson = await response.json()
    
    cookies().set(blalblabla)
    
} 


Something like that and this worked perfectly fine
Sun bearOP
It works, wow. Thank you
But i don't get the reason behind it yet
@Sun bear But i don't get the reason behind it yet
Toyger
as I said fetch itself return Promise, it's async, so it will eventually be executed, but you didn't await for that execution so you basically get pointer in memory to that Promise and function just exit for user and user get empty response, then in couple miliseconds it invoke on server but we have no one to set cookies for, because user already get response.
But when we add await our function will wait until this Promise will be finished, and only after all of it's then will be invoked we will send result to user with cookie that was in one of them
Sun bearOP
Ahhh okey, thank youuu!!!