Skip to content

Commit

Permalink
feat: create session cookie and set session cookie
Browse files Browse the repository at this point in the history
  • Loading branch information
m7ez1n committed Mar 15, 2023
1 parent 64e63b4 commit 4a56d09
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
25 changes: 25 additions & 0 deletions app/routes/action/set-theme.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { json } from '@remix-run/node';
import type { ActionFunction } from '@remix-run/node';

import { getThemeSession } from '~/utils/theme.server';
import { isTheme } from '~/utils/theme-provider';

export const action: ActionFunction = async ({ request }) => {
const themeSession = await getThemeSession(request);
const requestText = await request.text();
const form = new URLSearchParams(requestText);
const theme = form.get('theme');

if (!isTheme(theme)) {
return json({
success: false,
message: `theme value of ${theme} is not a valid theme`,
});
}

themeSession.setTheme(theme);
return json(
{ success: true },
{ headers: { 'Set-Cookie': await themeSession.commit() } },
);
};
34 changes: 34 additions & 0 deletions app/utils/theme.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createCookieSessionStorage } from '@remix-run/node';

import type { Theme } from './theme-provider';
import { isTheme } from './theme-provider';

const sessionSecret = process.env.SESSION_SECRET;
if (!sessionSecret) {
throw new Error('SESSION_SECRET must be set');
}

const themeStorage = createCookieSessionStorage({
cookie: {
name: 'my_remix_theme',
secure: true,
secrets: [sessionSecret],
sameSite: 'lax',
path: '/',
httpOnly: true,
},
});

async function getThemeSession(request: Request) {
const session = await themeStorage.getSession(request.headers.get('Cookie'));
return {
getTheme: () => {
const themeValue = session.get('theme');
return isTheme(themeValue) ? themeValue : null;
},
setTheme: (theme: Theme) => session.set('theme', theme),
commit: () => themeStorage.commitSession(session),
};
}

export { getThemeSession };

0 comments on commit 4a56d09

Please sign in to comment.