-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: create session cookie and set session cookie
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() } }, | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |