2

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

  • What file and/or function is that fetch request being made from? Is it being made from the client-side or server-side? Can you share the remaining code for that file? – juliomalves Jun 05 '22 at 22:47
  • The post has been edited. It now includes the entire index.tsx-file. – Emily Antosch Jun 07 '22 at 10:06
  • Cookies are not automatically sent when making a request from the server-side (`getServerSideProps`), you have to explicitly pass them. See [Why are cookies not sent to the server via getServerSideProps in Next.js?](https://stackoverflow.com/questions/69057271/why-are-cookies-not-sent-to-the-server-via-getserversideprops-in-next-js). – juliomalves Jun 07 '22 at 21:32

1 Answers1

0

The option headers: { 'Content-Type': 'application/json' } is unnecessary, because GET requests have no content type. But setting this header causes the browser to precede the GET request with a preflight request, to which your server probably does not respond as expected.

Please check if omitting this header solves the problem. If not, please check your browser's network trace and the filtered-out request cookies.

Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31
  • Dear Heiko, thanks for your response, the header option has been removed, but the server still cant receive the necessary token to validate my login. Kind regards, Emily – Emily Antosch Jun 05 '22 at 17:19
  • As far as I can see there are no filtered out request cookies in my trace, neither on the request im trying to sent through requesting '/' or by calling the api directly, both show the cookie in the network trace as non-filtered – Emily Antosch Jun 05 '22 at 17:52