Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active February 12, 2024 00:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanflorence/62121bda4454753f82b0f4062292da87 to your computer and use it in GitHub Desktop.
Save ryanflorence/62121bda4454753f82b0f4062292da87 to your computer and use it in GitHub Desktop.
import { createCookieSessionStorage } from "remix";
let { getSession, commitSession, destroySession } = createCookieSessionStorage({
cookie: {
name: "__session",
secrets: ["r3m1xr0ck5"]
}
});
export { getSession, commitSession, destroySession };
import {
useRouteData,
Form,
redirect,
json,
usePendingFormSubmit
} from "remix";
import { getSession, commitSession } from "../sessionStorage";
export async function action({ request }) {
// fake network lag
await new Promise(res => setTimeout(res, 1500));
let session = await getSession(request.headers.get("Cookie"));
// return session if we have it
if (session.has("id")) {
return redirect("/simple");
}
// set it if we don't
session.set("id", Date.now());
return redirect("/simple", {
headers: {
"Set-Cookie": await commitSession(session)
}
});
}
export async function loader({ request }) {
let session = await getSession(request.headers.get("Cookie"));
if (session.has("id")) {
return json(session.get("id"));
}
return null;
}
export default function Simple() {
let id = useRouteData();
let pendingSubmit = usePendingFormSubmit();
return (
<div>
<h1>Session ID: {id || "waiting ..."}</h1>
<Form replace method="post">
<button disabled={!!pendingSubmit}>
{pendingSubmit ? "Creating Session..." : "Create Session"}
</button>
</Form>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment