-1

I want to implement JWT auth in my Next app. Currently, I see the flow as following:

  • email and password are sent to the server to log in
  • server returns a response with status 200 and jwt access token in httpOnly cookies

The main problem is I don't really know which way to choose to go further. At every reloading page or starting of my Next app I want to fetch data about user, so there is endpoint, lets say /me, which returns info about the user and in the same time checks if the token expired.

Is this correct way to go down? Or it can be better? I went through every video tutorial and they just use old plain local storage, which is not very secure.

If this is a nice way, how to correctly implement this fetching of user data at every reload of app? I use Next 13

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
medreres
  • 19
  • 6

1 Answers1

0

the best way is on the top level of app, you make a request to /me endpoint. If you are using context api, inside Authorization context

"use client";
import axios from "axios";
import { getCookie } from "cookies-next";

const [authState, setAuthState] = useState({
   loading: true,
   data: null,
   error: null,
 });

const fetchUser = async () => {
   // we started the fetching process. so our app is loading
   setAuthState({
     data: null,
     error: null,
     loading: true,
   });
try {
  const jwt = getCookie("jwt");

  if (!jwt) {
    return setAuthState({
      data: null,
      error: null,
      loading: false,
    });
  }

  const response = await axios.get(`${process.env.BASE_URL/api/auth/m}`, {
    headers: {
      Authorization: `Bearer ${jwt}`,
    },
  });


  setAuthState({
    data: response.data,
    error: null,
    loading: false,
  });
} catch (error) {
  setAuthState({
    data: null,
    error: error.response.data.errorMessage || "Internal server error",
    loading: false,
  });
}
};

useEffect(() => {
    fetchUser();
}, []);

once you write authentication context, in any component, maybe in Navbar

 // you reach the auth state
   const { data, loading, error } = useContext(AuthenticationContext);

Based on this state values, you render the proper jsx

Yilmaz
  • 35,338
  • 10
  • 157
  • 202