#Global-error styles
1 messages · Page 1 of 1 (latest)
Hi @tawny solar. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To add styles to your global-error component in Next.js, you need to be aware of a few important points:
-
Global Styles vs. CSS Modules: Styles imported in
global-error.*from CSS modules will not apply unless they are also imported inlayout.*and somehow used there too. This is because Next.js doesn’t download the styles imported inglobal-error.*to the client even though it uses the class names on the elements. A clean way to circumvent this is to use global styles instead of importing a module. -
Using Global Styles: If you have a global styles file, you can create unique class names in this file with a globally unique prefix and then use them in
global-error.tsx. -
Hack for CSS Modules: If you really need to import CSS modules, you can use a hack to force the styles to load.
Here are the steps to add styles to your global-error component:
Using Global Styles
-
Create a global styles file (if you don't already have one) in your
appdirectory, e.g.,globals.scss. -
Import the global styles in your
layout.tsx:import './globals.scss'; -
Define unique class names in the global styles file:
// globals.scss .ErrorPage__container { background-color: #f8d7da; color: #721c24; padding: 20px; border: 1px solid #f5c6cb; } -
Use these class names in your
global-error.tsx:'use client'; export default function GlobalError({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { return ( <html> <body className="ErrorPage__container"> <h2>Something went wrong!</h2> <button onClick={() => reset()}>Try again</button> </body> </html> ) }
Using CSS Modules (Hack)
-
Create a CSS module file (e.g.,
error.module.scss):// error.module.scss .errorContainer { background-color: #f8d7da; color: #721c24; padding: 20px; border: 1px solid #f5c6cb; } // A dummy element to force load the styles in layout.tsx .dummy { display: none; } -
Import the CSS module in your
global-error.tsx:import Styles from '@/styles/error.module.scss'; -
Import the CSS module in your
layout.tsxand use the dummy class:import ErrorStyles from '@/styles/error.module.scss'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body> {children} <div className={ErrorStyles.dummy} /> </body> </html> ); } -
Use the styles in your
global-error.tsx:'use client'; import Styles from '@/styles/error.module.scss'; export default function GlobalError({ error, reset, }: { error: Error & { digest?: