Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

detecting user theme server-side

Blue Mouse5b7e1ea402d3
diff --git a/app/redux/constants/index.ts b/app/redux/constants/index.ts
index f61cc5698..6e8c1b049 100644
--- a/app/redux/constants/index.ts
+++ b/app/redux/constants/index.ts
@@ -232,6 +232,7 @@ export const SWETRIX_VS_SIMPLE_ANALYTICS: string = 'https://blog.swetrix.com/pos
export const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'
+export type ThemeType = 'dark' | 'light'
export const SUPPORTED_THEMES: string[] = ['light', 'dark']
export const CONTACT_EMAIL: string = '[email protected]'
diff --git a/app/redux/reducers/ui/theme.ts b/app/redux/reducers/ui/theme.ts
index ed617939c..47b8b1a8d 100644
--- a/app/redux/reducers/ui/theme.ts
+++ b/app/redux/reducers/ui/theme.ts
@@ -2,7 +2,7 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import _includes from 'lodash/includes'
import { setCookie, getCookie } from 'utils/cookie'
import {
- isBrowser, LS_THEME_SETTING, SUPPORTED_THEMES, THEME_TYPE,
+ isBrowser, LS_THEME_SETTING, SUPPORTED_THEMES, THEME_TYPE, ThemeType,
} from 'redux/constants'
const setThemeToDOM = (theme: string) => {
@@ -17,13 +17,17 @@ const setThemeToDOM = (theme: string) => {
root.classList.add(theme)
}
-const setTheme = (theme: string): string => {
+const setTheme = (theme: string, storeToCookie = true): string => {
setThemeToDOM(theme)
- setCookie(LS_THEME_SETTING, theme)
+
+ if (storeToCookie) {
+ setCookie(LS_THEME_SETTING, theme)
+ }
+
return theme
}
-const getInitialTheme = (): 'light' | 'dark' => {
+const getInitialTheme = (): ThemeType => {
if (!isBrowser) {
return 'light'
}
@@ -41,13 +45,13 @@ const getInitialTheme = (): 'light' | 'dark' => {
// return 'dark'
// }
- setTheme('light')
+ setTheme('light', false)
return 'light' // light theme as the default
}
interface IInitialState {
- theme: 'light' | 'dark'
- type: string
+ theme: ThemeType
+ type: string
}
const getInitialState = (): IInitialState => {
@@ -61,7 +65,7 @@ const themeSlice = createSlice({
name: 'theme',
initialState: getInitialState(),
reducers: {
- setTheme(state, { payload }: PayloadAction<'light' | 'dark'>) {
+ setTheme(state, { payload }: PayloadAction<ThemeType>) {
setTheme(payload)
state.theme = payload
},
diff --git a/app/root.tsx b/app/root.tsx
index 181a10280..ce45dc148 100644
--- a/app/root.tsx
+++ b/app/root.tsx
@@ -18,7 +18,7 @@ import {
whitelist, isBrowser, CONTACT_EMAIL, LS_THEME_SETTING,
} from 'redux/constants'
import {
- getCookie,
+ getCookie, generateCookieString,
} from 'utils/cookie'
import { ExclamationTriangleIcon, ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/24/outline'
import { Provider } from 'react-redux'
@@ -27,7 +27,6 @@ import _map from 'lodash/map'
// @ts-ignore
import { transitions, positions, Provider as AlertProvider } from '@blaumaus/react-alert'
import BillboardCss from 'billboard.js/dist/billboard.min.css'
-// import { getCookie } from 'utils/cookie'
import AlertTemplate from 'ui/Alert'
import { trackViews } from 'utils/analytics'
@@ -84,6 +83,7 @@ export const meta: V2_MetaFunction = () => [
]
export const headers: HeadersFunction = () => ({
+ // General headers
'access-control-allow-origin': '*',
'Cross-Origin-Embedder-Policy': 'require-corp; report-to="default";',
'Cross-Origin-Opener-Policy': 'same-site; report-to="default";',
@@ -92,6 +92,10 @@ export const headers: HeadersFunction = () => ({
'Referrer-Policy': 'strict-origin-when-cross-origin',
'X-Powered-By': 'Mountain Dew',
'X-XSS-Protection': '1; mode=block',
+ // Theme detection headers (browser hints)
+ 'Accept-CH': 'Sec-CH-Prefers-Color-Scheme',
+ Vary: 'Sec-CH-Prefers-Color-Scheme',
+ 'Critical-CH': 'Sec-CH-Prefers-Color-Scheme',
})
export function ErrorBoundary() {
@@ -178,7 +182,7 @@ export function ErrorBoundary() {
export async function loader({ request }: LoaderArgs) {
const { url } = request
const locale = detectLanguage(request)
- const theme = detectTheme(request)
+ const [theme, storeThemeToCookie] = detectTheme(request)
const isAuthed = isAuthenticated(request)
const REMIX_ENV = {
@@ -192,9 +196,16 @@ export async function loader({ request }: LoaderArgs) {
STAGING: process.env.STAGING,
}
+ const init = storeThemeToCookie ? {
+ headers: {
+ // 21600 seconds = 6 hours
+ 'Set-Cookie': generateCookieString(LS_THEME_SETTING, theme, 21600),
+ },
+ } : undefined
+
return json({
locale, url, theme, REMIX_ENV, isAuthed,
- })
+ }, init)
}
export const handle = {
diff --git a/app/routes/index.tsx b/app/routes/index.tsx
index 2463c10f4..a50f85ecd 100644
--- a/app/routes/index.tsx
+++ b/app/routes/index.tsx
@@ -17,7 +17,7 @@ export async function loader({ request }: LoaderArgs) {
return redirect('/login', 302)
}
- const theme = detectTheme(request)
+ const [theme] = detectTheme(request)
const isAuth = isAuthenticated(request)
return json({ theme, isAuth })
diff --git a/app/routes/login.tsx b/app/routes/login.tsx
index 93377c0a0..da4a17bbf 100644
--- a/app/routes/login.tsx
+++ b/app/routes/login.tsx
@@ -11,7 +11,7 @@ export const headers: HeadersFunction = ({ parentHeaders }) => {
}
export async function loader({ request }: LoaderArgs) {
- const theme = detectTheme(request)
+ const [theme] = detectTheme(request)
return json({ theme })
}
diff --git a/app/routes/projects.$id.tsx b/app/routes/projects.$id.tsx
index d3e523ac2..3724531a9 100644
--- a/app/routes/projects.$id.tsx
+++ b/app/routes/projects.$id.tsx
@@ -24,7 +24,7 @@ export const meta: V2_MetaFunction = ({ location }) => {
}
export async function loader({ request }: LoaderArgs) {
- const theme = detectTheme(request)
+ const [theme] = detectTheme(request)
return json({ theme })
}
diff --git a/app/routes/signup.tsx b/app/routes/signup.tsx
index 0b97f372e..fe3e16379 100644
--- a/app/routes/signup.tsx
+++ b/app/routes/signup.tsx
@@ -17,7 +17,7 @@ export async function loader({ request }: LoaderArgs) {
return redirect('/login', 302)
}
- const theme = detectTheme(request)
+ const [theme] = detectTheme(request)
return json({ theme })
}
diff --git a/app/utils/cookie.ts b/app/utils/cookie.ts
index 46f53cee6..a509bab32 100644
--- a/app/utils/cookie.ts
+++ b/app/utils/cookie.ts
@@ -18,12 +18,16 @@ export const getCookie = (key: string) => {
return null
}
+export const generateCookieString = (key: string, value: string | number | boolean, maxAge = 3600, sameSite = 'strict') => {
+ return `${key}=${value}; max-age=${maxAge}; path=/; SameSite=${sameSite}${COOKIE_SUFFIX}`
+}
+
export const setCookie = (key: string, value: string | number | boolean, maxAge = 3600, sameSite = 'strict') => {
if (!isBrowser) {
return null
}
- document.cookie = `${key}=${value}; max-age=${maxAge}; path=/; SameSite=${sameSite}${COOKIE_SUFFIX}`
+ document.cookie = generateCookieString(key, value, maxAge, sameSite)
}
export const deleteCookie = (key: string) => {
diff --git a/app/utils/server.ts b/app/utils/server.ts
index 9a07f5c5f..54d041f17 100644
--- a/app/utils/server.ts
+++ b/app/utils/server.ts
@@ -1,5 +1,6 @@
import routes from 'routesPath'
-import { TITLE_SUFFIX } from 'redux/constants'
+import _includes from 'lodash/includes'
+import { TITLE_SUFFIX, SUPPORTED_THEMES, ThemeType } from 'redux/constants'
export const hasAuthCookies = (request: Request) => {
const cookie = request.headers.get('Cookie')
@@ -9,15 +10,31 @@ export const hasAuthCookies = (request: Request) => {
return accessToken && refreshToken
}
-export function detectTheme(request: Request): 'dark' | 'light' {
+/**
+ * Function detects theme based on user's browser hints and cookies
+ *
+ * @param request
+ * @returns [theme, storeToCookie]
+ */
+export function detectTheme(request: Request): [ThemeType, boolean] {
+ // Stage 1: Check if user has set theme manually
const cookie = request.headers.get('Cookie')
- const theme = cookie?.match(/(?<=colour-theme=)[^;]*/)?.[0]
+ const theme = cookie?.match(/(?<=colour-theme=)[^;]*/)?.[0] as ThemeType
- if (theme === 'dark') {
- return 'dark'
+ if (_includes(SUPPORTED_THEMES, theme)) {
+ return [theme, false]
}
- return 'light'
+ // Stage 2: Try to detect theme based on Sec-CH browser hints
+ // Currently only Chromium-based browsers support this feature
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-Prefers-Color-Scheme
+ const hintedTheme = request.headers.get('Sec-CH-Prefers-Color-Scheme') as ThemeType
+
+ if (_includes(SUPPORTED_THEMES, hintedTheme)) {
+ return [hintedTheme, true]
+ }
+
+ return ['light', false]
}
export function getAccessToken(request: Request): string | null {