MERN

⌘K
  1. Home
  2. Docs
  3. MERN
  4. Font optimization

Font optimization

Step 1: Install the Font Package

First, you’ll need to install the font package for Next.js, which allows you to self-host Google Fonts:

npm install @next/font google
Bash

Step 2: Import Fonts in Your Code

Create a file for your fonts like src/fonts.js:





// src/fonts.js
import { Arimo, Roboto } from '@next/font/google';

export const arimo = Arimo({
  weight: ['400', '700'],
  display: 'swap',
  variable: '--primary-font',
});

export const roboto = Roboto({
  weight: ['300', '400', '500'],
  display: 'swap',
  variable: '--secondary-font',
});
JavaScript

Step 2: Import Fonts in Your Layout Component

Import the font configurations in your layout component

// src/components/layout.js
import { arimo, roboto } from '../fonts'; // Adjust the path according to your project structure

const Layout = ({ children }) => {
  return (
    <div className={`${arimo.variable} ${roboto.variable}`}>
      {/* Rest of your layout markup */}
      {children}
    </div>
  );
};

export default Layout;
JavaScript

Step 3: Use CSS Variables in Global Styles

Then, in your global CSS file or a CSS Module, you can use the CSS variables you’ve defined to set the fonts:

/* styles/globals.css */
:root {
  --primary-font: 'Arimo', sans-serif;
  --secondary-font: 'Roboto', sans-serif;
}

body {
  font-family: var(--primary-font);
}

h1, h2, h3, p, ul, li {
  font-family: var(--secondary-font);
}

JavaScript

Make sure your global CSS is imported in your _app.js so it applies to the entire application:





// pages/_app.js
import '../styles/globals.css';

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}
JavaScript

Step 4: Use Layout in Your Pages

Now, use the Layout component in your pages to wrap the page content:





// pages/index.js or any other page
import Layout from '../components/layout';

const HomePage = () => {
  return (
    <Layout>
      {/* Your page content */}
      <h1>Welcome to My Page</h1>
    </Layout>
  );
};

export default HomePage;
JavaScript

How can we help?