Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Define a function to check if the localStorage key exists:
function isLoggedIn() {
  return !!localStorage.getItem('token');
}

This function will return true if the 'token' key exists in the localStorage.

  1. In the load function of the pages that require authentication, check if the user is authenticated:
export async function load({ session }) {
  if (!isLoggedIn()) {
    return {
      status: 401,
      redirect: '/login'
    };
  }

  // Return the data for the page
}

This will redirect the user to the login page if they are not authenticated.

  1. In the login or registration process, save the token to the localStorage:
localStorage.setItem('token', token);
  1. In the logout process, remove the token from the localStorage:
localStorage.removeItem('token');

This will log the user out and remove the authentication token from the localStorage.

By following these steps, your routes will be protected and only accessible to authenticated users.