I would like to understand how cookie session works in React Router, I would like to create a register form and use session storage in React Router.
I don't understand how to save cookie session userid and retrieve it.
Under action I save a cookie session with one userId and I want retrieve it at startup with the function under loader, but I think the cookie session doesn't persist.
import { createBrowserRouter, type ActionFunction, redirect } from "react-router";
import Home from "./components/Home"
import Page from "./components/Page";
import Login from "./components/Login";
import Register from "./components/Register"
import {
getSession,
commitSession,
} from "./sessions.server";
export const router = createBrowserRouter([
{
path: "/",
Component: Page,
loader: async ({request}) => {
const session = await getSession(
request.headers.get("Cookie"),
);
console.log(session.has("userId"))
if (session.has("userId")) {
// Redirect to the home page if they are already signed in.
console.log("LOGGED IN")
}
console.log("NO")
},
children:
[{
index: true,
Component: Home
}, {
path: "login",
Component: Login
}, {
path: "register",
Component: Register,
action: async ({ request }) => {
const session = await getSession(
request.headers.get("Cookie"),
);
let formData = await request.formData();
let email = formData.get("email")
let password = formData.get("password")
let register = await fetch("http://localhost:3000/register", {
method: "POST",
body: JSON.stringify({ email, password }),
headers: { 'Content-Type': 'application/json' }
})
let response = await register.json()
let userId = response.id
if (userId == null) {
session.flash("error", "Invalid username/password");
// Redirect back to the login page with errors.
return redirect("/register", {
headers: {
"Set-Cookie": await commitSession(session),
},
});
}
session.set("userId", userId);
// Login succeeded, send them to the home page.
return redirect("/", {
headers: {
"Set-Cookie": await commitSession(session),
},
});
}
}
]
},
]);