Blog>
Snippets

Global Stylesheets and Theming with Next.js

Exhibit how to import and apply global stylesheets, fonts, and theme configurations in a Next.js application.
// styles/global.css
body {
  margin: 0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

// Import your global stylesheet in pages/_app.js
import '../styles/global.css';

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}
In your global.css file, define the styles you want to apply to your whole application. Then, in pages/_app.js, import the global stylesheet to apply these styles to all pages of your Next.js application.
// Example of theme configuration with styled-components in Next.js

// 1. Create a theme.js file to store your theme variables
// theme.js
export const theme = {
  colors: {
    primary: '#0070f3',
    // ... other colors
  },
  // ... other theme-related styling
};

// 2. Apply the theme using the ThemeProvider in pages/_app.js
import { ThemeProvider } from 'styled-components';
import { theme } from '../path/to/theme.js';

export default function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider theme={theme}>
      <Component {...pageProps} />
    </ThemeProvider>
  );
}
Create a theme configuration in a theme.js file. Use styled-components' ThemeProvider in pages/_app.js to make the theme available throughout your application, which can then be accessed through the use of the `useTheme` hook or `withTheme` HOC in your styled components.
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap');

body {
  font-family: 'Open Sans', sans-serif;
}
In your CSS file, you can import external fonts like Google Fonts and define them for usage in your document. Add this snippet to your global.css or any other relevant CSS file.
// Next.js configuration to use custom document - pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <link rel="preconnect" href="https://fonts.gstatic.com" />
          <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
To include a font across your entire Next.js application, you can insert a <link> tag in the custom _document.js file. This ensures the font is loaded on the initial server-side render.