Primate Logo Primate
Guides Responses

Redirect to login page

To conditionally redirect to a login page based on session status, create a hook 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 hook file inside the top routes directory applies to all routes of your application. If you want to limit the hook to certain routes, place it in a subdirectory.

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

export default hook((request, next) => {
  // if at login page or session exists, pass through
  if (request.url.pathname === "/login" || session.exists()) {
    return next(request);
  }

  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";

export default route({
  get() {
    return response.view("Login.jsx");
  },
  post(request) {
    // do verification work, create session, etc.

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