Performance: Creating and destroying sessions
This concept affects page load speed and interaction responsiveness by managing how session data is stored and cleared, impacting server response time and client-side rendering.
export async function loader({ request }) { const session = await getSession(request.headers.get('Cookie')); if (!session.has('userId')) { // Only create session once when needed session.set('userId', generateRandomId()); return redirect('/dashboard', { headers: { 'Set-Cookie': await commitSession(session) } }); } return json({ userId: session.get('userId') }); } export async function action({ request }) { const session = await getSession(request.headers.get('Cookie')); // Destroy session cleanly on logout return redirect('/login', { headers: { 'Set-Cookie': await destroySession(session) } }); }
export async function loader({ request }) { const session = await getSession(request.headers.get('Cookie')); if (!session.has('userId')) { // Create a new session with default data on every request session.set('userId', generateRandomId()); return redirect('/dashboard', { headers: { 'Set-Cookie': await commitSession(session) } }); } return json({ userId: session.get('userId') }); } export async function action({ request }) { const session = await getSession(request.headers.get('Cookie')); // Destroy session on logout return redirect('/login', { headers: { 'Set-Cookie': await destroySession(session) } }); }
| Pattern | Server Session Writes | Response Size | User Interaction Delay | Verdict |
|---|---|---|---|---|
| Create session on every request | Multiple writes | Larger due to repeated Set-Cookie | Higher INP due to server delay | [X] Bad |
| Create session only when missing | Single write per session | Smaller, minimal Set-Cookie headers | Lower INP, faster response | [OK] Good |
destroySession(session) in Remix?const session = await sessionStorage.getSession(request.headers.get('Cookie'));
const response = new Response('Logged out');
return redirect('/login', {
headers: {
'Set-Cookie': await sessionStorage.destroySession(session)
}
});const session = await sessionStorage.getSession(request.headers.get('Cookie'));
return redirect('/logout', {
headers: {
'Set-Cookie': sessionStorage.destroySession(session)
}
});1. Get the current session from the request cookie.
2. Destroy the session to clear cookie data.
3. Redirect the user to the login page with the destroyed session cookie set.
4. Create a new session with empty data before redirecting.
Pass the test and this pattern moves unknown