SolidJSS
SolidJSβ€’12mo agoβ€’
3 replies
Amir Hossein Hashemi

I can't initialize a session

In this code, I use useSession to create a session and initialize it with "light" if it doesn't have a value:

import { createAsync, query } from "@solidjs/router";
import { useSession } from "vinxi/http";

type SessionData = {
  theme: "light" | "dark";
};

const getTheme = query(async () => {
  "use server";
  const session = await useSession<SessionData>({
    password: process.env.SESSION_SECRET as string,
    name: "theme",
  });

  if (!session.data.theme) {
    await session.update({
      theme: "light",
    });
  }

  return session.data.theme;
}, "getTheme");

export function ThemeToggle() {
  const theme = createAsync(() => getTheme());

  return <p>theme: {theme()}</p;
}


When I start the application for the first time, or when I manually remove the theme cookie in the devtools and refresh the page, I get this error:

Cannot set headers after they are sent to the client


I don't exactly understand why I get the error. In seems like calling useSession immediately sends the response to the client, so session.update() fails because the response is already sent. That's not what expected to happen. Am I doing something wrong?
Was this page helpful?