I am creating the login functionalities of my website but having trouble with setting the Cookie with the token from my backend. The token is being returned properly and is setting the user in the UserContext, however the part where the token is to be stored in the browser Cookie (such as when viewed in the browser developer options Application
tab) it is not showing or being set. I have no idea whether the issue is in the Login.jsx
or in the useStorage.js
. Here are the current codes:
./src/hooks/useStorage.js
import { useCallback, useEffect, useState } from 'react';
import Cookies from 'js-cookie';
function useLocalStorage(key, defaultValue) {
return useStorage(key, defaultValue, window.localStorage);
};
function useSessionStorage(key, defaultValue) {
return useStorage(key, defaultValue, window.sessionStorage);
};
function useCookiesStorage(key, defaultValue, options) {
return useStorage(key, defaultValue, null, options);
};
function useStorage(key, defaultValue, storageObject, options) {
const [value, setValue] = useState(() => {
if (storageObject) {
const jsonValue = storageObject.getItem(key);
if (jsonValue != null) return JSON.parse(jsonValue);
} else {
const cookieValue = Cookies.get(key);
if (cookieValue != null) return JSON.parse(cookieValue);
}
if (typeof defaultValue === "function") {
return defaultValue();
} else {
return defaultValue;
}
});
useEffect(() => {
if (value === undefined) {
if (storageObject) {
return storageObject.removeItem(key);
} else {
return Cookies.remove(key, options);
}
}
const jsonValue = JSON.stringify(value);
if (storageObject) {
storageObject.setItem(key, jsonValue);
} else {
Cookies.set(key, jsonValue, options);
}
}, [key, value, storageObject, options]);
const remove = useCallback(() => {
setValue(undefined);
}, []);
return [value, setValue, remove];
};
export {
useLocalStorage,
useSessionStorage,
useCookiesStorage
};
./src/pages/Login.jsx
import '../assets/css/login.css';
import { Button, Col, Container, Form, Image, InputGroup, Row, Stack } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useContext, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { GetUser, SignIn } from '../utils/Auth';
import Swal from 'sweetalert2';
import { useCookiesStorage } from '../hooks/useStorage';
import UserContext from '../UserContext';
function Login() {
const { setUser } = useContext(UserContext);
const navigate = useNavigate();
const [uidValue, setUidValue] = useState('');
const [upassValue, setUpassValue] = useState('');
const [,setToken] = useCookiesStorage('__Secure-auth.session-token', null, {httpOnly: true, secure: true, sameSite: 'Strict'});
async function LoginUser(e) {
e.preventDefault();
Swal.fire({
title: 'Logging in',
didOpen: () => {
Swal.showLoading();
},
text: 'Please wait',
showConfirmButton: false,
allowOutsideClick: false
});
const response = await SignIn(uidValue, upassValue); // Returns response message and token
if (!response || !response.token) {
Swal.close();
Swal.fire({
title: `${response.message}!`,
icon: 'error',
text: 'Try again',
timer: 2000,
timerProgressBar: false,
showConfirmButton: false,
allowOutsideClick: false
});
}
else {
setToken(response.token); // Set the Cookie '__Secure-auth.session-token'
const user = await GetUser(response.token); // returns user details
if (!user || !user._id) {
Swal.close();
Swal.fire({
title: `${response.message}!`,
icon: 'error',
text: 'Try again',
timer: 2000,
timerProgressBar: false,
showConfirmButton: false,
allowOutsideClick: false
});
}
else {
Swal.close();
Swal.fire({
title: 'Login successful!',
icon: 'success',
text: 'Redirecting to dashboard, please wait...',
timer: 2000,
timerProgressBar: false,
showConfirmButton: false,
allowOutsideClick: false
})
.then((result) => {
if (result.dismiss === Swal.DismissReason.timer) {
setUidValue('');
setUpassValue('');
setUser({ // Sets user context with details from fetch request
uid: user._id,
user: user.username,
role: user.role
});
navigate('/dashboard');
}
});
}
}
};
return (...rest of code);
};
export default Login;
I hope someone could help me with what I am doing wrong, I am fairly new to React JS and studying through project based learning.