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;
}
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
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?
2 Replies
Brendonovich
Brendonovich2w ago
Try adding deferStream to the createAsync, it may at least fix the error I think updating headers during SSR while streaming isn’t really supported
Amir Hossein Hashemi
Thanks, deferStream = true fixed the error.

Did you find this page helpful?