I would like to send 'cookieValue' to my backend but I'm not quite sure how to and haven't been able to find any good resources online.
Currently, I don't believe that my 'cookieValue' actually has a value when I try to send it to my backend. I am also getting a waring saying that 'cookieValue' is declared but never used in my 'findCookie function'. Below I have my current code, any help would be appreciated.
Front End Code:
import axios from 'axios'
import { Outlet, Navigate } from "react-router";
import { useState } from 'react'
let backEndResponse = null
function SendCookie() {
const [cookieValue, setCookieValue] = useState("");
if (document.cookie != null) {
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith('Auth='))
.split('=')[1];
axios.post('http://localhost:5000/auth', {
cookieValue,
}).then(getBackEndResponse => {
return axios.get('http://localhost:5000/auth', { withCredentials: true }).then((res) => {
res.render(backEndResponse);
})
});
} else {
}
}
const useAuth = () => {
if (backEndResponse) {
const authorized = {loggedIn: true}
return authorized && authorized.loggedIn;
} else {
const authorized = {loggedIn: false}
return authorized && authorized.loggedIn;
}
};
const ProtectedRoutes = () => {
const isAuth = useAuth();
return isAuth ? <Outlet/> : <Navigate to="/login" />;
}
export default ProtectedRoutes
Backend Code:
app.post('/auth', (req, res) => {
const authCookie = req.body.cookieValue
if (authCookie === result) {
backEndResponse = true
} else {
backEndResponse = false
}
});
app.get('/auth', (req, res) => {
res.render(backEndResponse)
});
Cookies come from your backend, and the browser will automatically send them back with any subsequent request to the same backend. Your backend can access them as res.cookies. You need not write any extra code for that.