Next.js Discord

Discord Forum

Cookie do not get set in browser

Unanswered
Broad-snouted Caiman posted this in #help-forum
Open in Discord
Broad-snouted CaimanOP
i have a backend in golang that sends me back cookies once i log in

i ll share the login page i have
'use client'

import React, {useState } from 'react';
import { useRouter } from 'next/navigation';

export default function LoginC() {
  const [formData, setFormData] = useState({
    email: '',
    password: ''
  });

  const [error, setError] = useState('');


  const router = useRouter()

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault(); // Prevent the default form submission
    setError('');
    try {
      const response = await fetch('http://localhost:8787/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });

      if (response.status === 401) {
        const errorData = await response.json();
        setError(errorData.message); // Update the error state
        return;
      }

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText);
      }

      router.push('/dashboard')
      
    } catch (error) {
      setError('An unexpected error occurred. Please try again.');
      console.error('Error:', error);
    }
  };

  return ...


this is the raw response i get from my backend

HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Content-Type: application/json
Set-Cookie: token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImV4cCI6MTcxNzYwNjYyMX0.WZuoh2ud-ALSxwRDM0ZD0hA75u29qzIZtds9N6Agu38; Path=/; Max-Age=168; HttpOnly; SameSite=None
Vary: Origin
Date: Wed, 05 Jun 2024 14:57:01 GMT
Content-Length: 0


but the browser wont save the cookie on the cookies storage so i cant access the other api that requires me to be authenticated with and send the cookie alang

0 Replies