SolidJSS
SolidJSโ€ข2y agoโ€ข
8 replies
exercise

Race condition

i have a login page with a login action like this:
const login = action(async (formData: FormData) => {
  ("use server");
  const username = formData.get("username");
  const password = formData.get("password");
  if (typeof username === "string" && typeof password === "string") {
    const foundUser = await db.query.user.findFirst({
      where: eq(user.username, username),
    });

    if (!foundUser || !(await verify(foundUser.password, password)))
      return new Error("Wrong username or password");

    const session = await lucia.createSession(foundUser.id, {});
    const sessionCookie = lucia.createSessionCookie(session.id);

    setCookie(
      sessionCookie.name,
      sessionCookie.value,
      sessionCookie.attributes
    );
    // this is happening before the cookie gets set
    throw redirect("/");
  }
}, "login");

and an index page that checks the user:
const getUser = cache(async () => {
  "use server";

  const sessionId = getCookie(lucia.sessionCookieName);

  if (!sessionId) throw redirect("/login");
  const { user } = await lucia.validateSession(sessionId);

  if (!user) throw redirect("/login");

  return user;
}, "user");

export const route = {
  load: () => getUser(),
};

when /login redirects to / after submitting the action, somehow / doesn't have the new cookie.
Was this page helpful?