Using the Google Fonts API with Next.js and TypeScript the right way.

Fonts are an integral part of your project and having your choice and knowing how to implement it can make you feel really excited to keep going on with the project.

Emmanuel Unyime
Geek Culture

--

Prerequisites — Just Two

  • A Next.js project initialized with TypeScript.
npx create-next-app@latest --ts
// or
yarn create next-app --typescript
  • Text to apply your fonts.

Using CDN is not really a go-to practice in a NextJs project because at first glance unlike React there is no index.html file (App entry point). Popular libraries like Tailwind and AntCSS have npm packages as “best practices” in web apps built with frameworks.

However, there are exceptions to this and one of them is Google Fonts. Let us explore two methods of implementation for Google Fonts on your project:

  1. Using the _document.tsx file(Recommended)

A sample Next js _document.tsx file

Here we use the font CDN like a normal HTML project but links like that are to go into a _document.tsx(jsx) file

2. Importing Font Url

This does not particularly work if you have your font files but except the font does not exist on Google Fonts, I strongly recommend the first method. Here we import fonts via the generated google fonts site and then declare them in CSS.

NOTE: This is to be done in the globals.css file of your project because it is this CSS file that is your general file and changes here affect all pages across your entire application

--

--

Emmanuel Unyime
Geek Culture

I’m a Software Engineer && Technical Writer, I've had the TypeScript epiphany!. Oh, I play Chess too!