createCookieSessionStorage

tsx
const storage = createCookieSessionStorage();
tsx
const storage = createCookieSessionStorage();


Usage

Creating a SessionStorage

tsx
import { createCookieSessionStorage } from 'solid-start';
 
const storage = createCookieSessionStorage({
cookie: {
name: "session",
secure: process.env.NODE_ENV === "production",
secrets: [process.env.SESSION_SECRET],
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30, // 30 days
httpOnly: true
}
});
tsx
import { createCookieSessionStorage } from 'solid-start';
 
const storage = createCookieSessionStorage({
cookie: {
name: "session",
secure: process.env.NODE_ENV === "production",
secrets: [process.env.SESSION_SECRET],
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30, // 30 days
httpOnly: true
}
});

Reading the session data of the current request

tsx
async function getUserId(request: Request) {
const session = await storage.getSession(request.headers.get("Cookie"));
 
const userId = session.get("userId");
return userId;
}
tsx
async function getUserId(request: Request) {
const session = await storage.getSession(request.headers.get("Cookie"));
 
const userId = session.get("userId");
return userId;
}

Writing the session data for the current request

tsx
async function login(request: Request, userId: string) {
const session = await storage.getSession(request.headers.get("Cookie"));
session.set("userId", userId);
const response = new Response("Logged in", {
headers: {
"Set-Cookie": await storage.commitSession(session)
}
});
}
tsx
async function login(request: Request, userId: string) {
const session = await storage.getSession(request.headers.get("Cookie"));
session.set("userId", userId);
const response = new Response("Logged in", {
headers: {
"Set-Cookie": await storage.commitSession(session)
}
});
}

Deleting the session data for the current request

tsx
import { redirect } from "solid-start";
 
async function logout(request: Request) {
const session = await storage.getSession(request.headers.get("Cookie"));
 
return redirect("/login", {
headers: {
"Set-Cookie": await storage.destroySession(session)
}
});
}
tsx
import { redirect } from "solid-start";
 
async function logout(request: Request) {
const session = await storage.getSession(request.headers.get("Cookie"));
 
return redirect("/login", {
headers: {
"Set-Cookie": await storage.destroySession(session)
}
});
}

Creating a new session

tsx
async function signUp(request: Request, userId: string) {
const session = await storage.getSession();
session.set("userId", userId);
return new Response("Signed Up", {
headers: {
"Set-Cookie": await storage.commitSession(session)
}
});
}
tsx
async function signUp(request: Request, userId: string) {
const session = await storage.getSession();
session.set("userId", userId);
return new Response("Signed Up", {
headers: {
"Set-Cookie": await storage.commitSession(session)
}
});
}