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
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.