Primate Logo Primate
Guides Responses

Redirect to login page

To conditionally redirect to a login page based on session status, create a guard file inside routes and check if the user has a valid session. If not, redirect to /login with request.target (pathname and query string).

A guard file inside the top routes directory applies to all routes of your application. If you want to limit the guard to certain routes, place it in a subdirectory.

TypeScriptroutes/+guard.ts
import session from "#session";
import response from "primate/response";
import route from "primate/route";

route.get(request => {
  // if at login page or session exists, pass through
  if (request.url.pathname === "/login" || session.exists()) {
    return null;
  }

  return response.redirect(`/login?next=${request.target}`);
});

Inside your /login route, read the next query parameter to redirect back to the page the user came from.

TypeScriptroutes/login.ts
import response from "primate/response";
import route from "primate/route";

route.get(() => response.view("Login.jsx"));

route.post(request => {
  // do verification work, create session, etc.

  return response.redirect(request.query.get("next"));
});