Trouble determining theme on serverside
Answered
Sjoerd posted this in #help-forum
SjoerdOP
I want to determine the theme of the user on the serverside. I use the app router. I have this logic now:
layout.tsx
export default async function RootLayout(props: LayoutProps) {
const initialTheme = getInitialTheme();
return (
<html data-theme={initialTheme} lang="en">
<body className={inter.className}>
<Navigation />
<main className={styles.main}>{props.children}</main>
</body>
</html>
);
}
theme.ts
import { NextApiRequest } from 'next';
export function getInitialTheme(req: NextApiRequest): string {
const cookieTheme = req.cookies['theme'];
if (cookieTheme) {
return cookieTheme;
}
const prefersDarkMode = req.headers['user-agent']
? req.headers['user-agent'].includes('DarkMode')
: false;
return prefersDarkMode ? 'dark' : 'light';
}
How can i pass the req parameter in layout.tsx?
layout.tsx
export default async function RootLayout(props: LayoutProps) {
const initialTheme = getInitialTheme();
return (
<html data-theme={initialTheme} lang="en">
<body className={inter.className}>
<Navigation />
<main className={styles.main}>{props.children}</main>
</body>
</html>
);
}
theme.ts
import { NextApiRequest } from 'next';
export function getInitialTheme(req: NextApiRequest): string {
const cookieTheme = req.cookies['theme'];
if (cookieTheme) {
return cookieTheme;
}
const prefersDarkMode = req.headers['user-agent']
? req.headers['user-agent'].includes('DarkMode')
: false;
return prefersDarkMode ? 'dark' : 'light';
}
How can i pass the req parameter in layout.tsx?
Answered by B33fb0n3
you don't have access to the request in layouts. However you can still access cookies using the
cookies() function. And you can also access headers using the headers() function. Use them and get your values4 Replies
@Sjoerd I want to determine the theme of the user on the serverside. I use the app router. I have this logic now:
layout.tsx
export default async function RootLayout(props: LayoutProps) {
const initialTheme = getInitialTheme();
return (
<html data-theme={initialTheme} lang="en">
<body className={inter.className}>
<Navigation />
<main className={styles.main}>{props.children}</main>
</body>
</html>
);
}
theme.ts
import { NextApiRequest } from 'next';
export function getInitialTheme(req: NextApiRequest): string {
const cookieTheme = req.cookies['theme'];
if (cookieTheme) {
return cookieTheme;
}
const prefersDarkMode = req.headers['user-agent']
? req.headers['user-agent'].includes('DarkMode')
: false;
return prefersDarkMode ? 'dark' : 'light';
}
How can i pass the req parameter in layout.tsx?
you don't have access to the request in layouts. However you can still access cookies using the
cookies() function. And you can also access headers using the headers() function. Use them and get your valuesAnswer
@Sjoerd Thank you so much!
Happy to help. Please mark solution