I'm struggling with the following problem: I'm trying to send a cookie with a GET-Request to find out if the user is logged in or not. The cookie has been successfully sent to my browser and I can therefore view it in my developer tools. Making a request through the URL-Bar to the API works and I get the correct response of
{loggedIn : true}
But if I call the url programatically through
const Response = fetch('http://localhost:3001/api/auth/loggedIn', requestOption)
.then((res) => {
return res.json()
}).then(json => {return json.loggedIn})
var loggedIn = await Response
console.log(loggedIn)
The console always reads false and I get redirected to the login page (happens every time the user is seemingly not logged in).
Do you have any idea what I could try to fix the issue? My frontend runs on Next.js, the Backend on Express.js The RequestOptions passed to fetch() currently is:
const requestOption = {
method: "GET",
mode: 'cors' as RequestMode,
credentials: 'include' as RequestCredentials,
headers: { 'Content-Type': 'application/json' },
}
EDIT: as requested, here is the rest of the code for my index.tsx-file. The request, as far as I know, is being made from the server-side in getServerSideProps().
import type { NextPage } from 'next'
import { useState } from 'react'
import Navbar from '../components/Navbar'
import HeroDash from '../components/hero_dash'
import CookieBanner from '../components/CookieBanner'
import Tutorial from '../components/Tutorial'
import Outset from '../components/Outset'
const Home: NextPage = () => {
const handleSearchClick = () => {
setSearchIcon(!searchIcon)
console.log(searchIcon)
}
const [searchIcon, setSearchIcon] = useState(false)
return (
<>
<div className="h-screen bg-cultured dark:bg-raisin">
<Navbar />
<HeroDash />
<div className="columns-2 gap-x-10 px-10">
<div className="break-after-column">
<Outset />
</div>
<div className="">
<Tutorial />
</div>
</div>
<div className="flex justify-center">
<CookieBanner hidden={true} />
</div>
</div>
</>
)
}
export default Home
export async function getServerSideProps() {
const requestOption = {
method: 'GET',
credentials: 'include' as RequestCredentials,
}
const Response = fetch(
'http://localhost:3001/api/auth/loggedIn',
requestOption
)
.then((res) => {
return res.json()
})
.then((json) => {
console.log(json.loggedIn)
return json.loggedIn
})
var loggedIn = await Response
console.log(loggedIn)
if (!true) {
return {
redirect: {
destination: '/login',
permanent: false,
},
}
}
return {
props: {},
}
}
Thank you in advance and have a wonderful weekend
Emily