My express server is not saving the JWT in cookies

I’m trying to make a blog with react and express with sql but when I’m trying to save the JWT into a cookie the browser just don’t save it, I don’t get it because there is no error in the console or the browser, it returns a 200 and the login page redirects to main but doesn’t save the cookie:

here is my login controller:

export const login = (req, res) => {
    //Check if the user exists
    const q = "SELECT username, password FROM blog.users WHERE username = ?;"
    db.query(q, [req.body.username], (err, [data])=>{
        if(err) return res.json(err);
        if(data === undefined) return res.status(404).json('User not found!');

        //Check password and generate jwt

        bcrypt.compare(req.body.password ,data.password)
            .then((passwordCheck)=>{
                if(!passwordCheck) return res.status(400).json('Wrong password');
                const {password, ...other} = data;
                jwt.sign({id: data.id}, 'chop_suey', (err, token)=>{
                    if(err){
                        console.log(err)
                        return res.status(500).json('')
                    }
                    res.cookie('access_token', 'eso brad', {
                        httpOnly: true,
                        secure: true,
                    }).status(200).json(other)
                });   
            })
            .catch((err)=>{
                console.log(err)
                return res.status(500).json('Server error: password check failed')
            })

        


    })
}

this is the index where I configured the cookie parser:

import express from 'express'
import authRoutes from "./routes/auth.js"
import userRoutes from "./routes/users.js"
import postRoutes from "./routes/posts.js"
import cookieParser from 'cookie-parser'


const app = express();
const port = 8800;

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    if (req.method === 'OPTIONS') {
        return res.sendStatus(204);
    }
    next();
});

app.use(express.json())
app.use(cookieParser())
app.use('/api/auth', authRoutes)
app.use('/api/users', userRoutes)
app.use('/api/posts', postRoutes)


app.listen(port, ()=>{
    console.log(`Servidor montado en el puerto ${port}`)
})

and the front:

import {useState} from 'react'
import {Link, useNavigate} from 'react-router-dom'
import axios from 'axios'

const Login = () => {

  const [inputs, setInputs] = useState({
    username: '',
    password: ''
  });

  let [err, setError] = useState(null);

  const navigate = useNavigate();

  const handleChange = e => {
    setInputs(prev=>({...prev, [e.target.name]: e.target.value}))
  }

  const handleClick = async (e) => {
    e.preventDefault()  
    try{
      await axios.post('http://localhost:8800/api/auth/login', inputs);
      setError(err = null)
      setTimeout(()=>{
        navigate("/")
      }, "1000");
    } catch(err){
      if(err){
        console.log(err)
        setError(err.response.data)  
      }
    }
  }

  return (
    <div className="auth">
      <h1>Login</h1>
      <form>
        <input name="username" type="text" placeholder='Username' onChange={handleChange}/>
        <input name="password" type="password" placeholder='Password' onChange={handleChange}/>
        <button onClick={handleClick}>login</button>
        {err && <p>{err}</p>}
        <span>Don't you have an account? <Link to='/register'>register</Link></span>
      </form>
    </div>
  )
}

export default Login

I’ll configure the secret kay for the JWT later in a environment variant :p

I just want that the JWT gets stored in a cookie on the browser for the session

New contributor

Juan Carlos Muñoz Pico is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật