Blog

Our Blog

We help junior tech professionals, such as developers and designers, to grow.

Using Google Fonts with Next.js (typescript)

Cheryl M   2022-11-08

Blog post cover

To add a google font to an Next.js application, create a Custom Document ( _document.tsx in the pages folder), and copy from google fonts

image.png

// pages/_document.tsx
import Document, {
    DocumentContext,
    DocumentInitialProps,
    Html,
    Head,
    Main,
    NextScript
} from 'next/document'

class MyDocument extends Document {
    static async getInitialProps(
        ctx: DocumentContext
    ): Promise<DocumentInitialProps> {
        const initialProps = await Document.getInitialProps(ctx)

        return initialProps
    }

    render() {
        return (
            <Html>
                <Head>
                    <link rel="preconnect" href="https://fonts.googleapis.com"/>
                    <link rel="preconnect" href="https://fonts.gstatic.com"/>
                    <link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet"/>
                </Head>
                <body>
                <Main/>
                <NextScript/>
                </body>
            </Html>
        )
    }
}

export default MyDocument
Enter fullscreen mode Exit fullscreen mode

Finally, apply this CSS rule

image.png

Author Bio

Author's profile

Cheryl is a Full-Stack web and mobile developer who loves learning and creating tools to make life easier and improve efficiency. She also enjoys problem-solving and helping new developers

Github LogoLinkedin account of Web Dev Path

Still got questions?

Feel free to contact us.
Contact us
Hashtag