Search code examples
reactjscookiesspring-securitysetcookie

Correct way to handle JWT tokens in cookies for authentication on the client-side


I have a backend that responds with a JWT token upon successful authentication. However, for security purposes, the cookie can not be visible from the client-side. Now in the frontend I use react. I have created a functional component that sets and gets a token. I have learned that the best approach to store the JWT token is to save it as a cookie as well as activate HTTPOnly from server side. The question I have is for the purpose of securing the JWT token how can I properly save the cookie in the frontend if the HTTPOnly is activated (which makes the cookie not visible)? I plan to use the cookie to check if the user is already logged in or not. Just to give you an overview of what I am doing I have added the component below.


export default function useToken() {
    const getToken = () => {
        const tokenString = localStorage.getItem("token"); // I will refactor localstorage to cookie
        const userToken = JSON.parse(tokenString as string);
        return userToken;
    }

    const [token, setToken] = useState<string>(getToken());

    const saveToken = (userToken: string) => {
        localStorage.setItem("token", JSON.stringify(userToken)); // I will refactor localstorage to cookie
        setToken(userToken)
    }
    return {
        setToken: saveToken, 
        token
    }
}


......

  const { token, setToken } = useToken()
  return (
    <div className="app">
      <Header />
      <Footer />

      <Router>
        <Routes>
          <Route path="/login" element={!token ? <Login setToken={setToken} /> : <Navigate to="/" />} />

.....

Solution

  • To check if the user is already logged in or not, one common way is :

    as soon as one request from the backend returns HTTP 401, the user is considered logged out.

    Also, it depends if your frontend is in a CDN or hitting the server on page load. On the latter case, you can find it out server-side.

    Then, to handle authentication, your server can read the JWT token from the cookies when receiving the request.