Using Google fonts with Remixjs, TailwindCSS and Fontsource
This is the beginning of my Remix.js journey. I’ve decided that Next.js and I needed a break. Although I’ve read many of the complaints developers have about Next.js, that’s not why I decided to try Remix.js. I kept coming across articles where developers loved their experience with Remix.js. I also appreciate that Remix.js closely follows web standards.
Next.js can sometimes feel like a magic box, it does offer great features—one of the best being font optimization. This was the first question I asked myself when I opened up my VSCode editor. My goal was to mimic, as closely as possible, what the Next.js next/font module does: automatic self-hosting with no network requests. I’m open to discussing other methods, but below is what I ended up doing.
For grabbing fonts, I decided to use Fontsource. It has several advantages:
Performance: No network requests to Google’s CDN.
Version Locking: Google regularly updates its fonts, but with Fontsource, you can lock the version.
Privacy: Using Fontsource avoids Google tracking the usage of their fonts.
Offline Support: Fonts load even when you’re offline.
Additional Font Options: Fontsource supports more than just Google Fonts.
Since my first Remix.js project is to convert my portfolio website from Next.js, I wanted to continue using the two fonts I have there: Open Sans and Playfair Display.
To load the fonts on the front end, you need to add the following lines to your root.tsx file.
To display the fonts with TailwindCSS, there are two approaches. I prefer to load them globally, so I don’t have to repeatedly specify them in the HTML class attribute. Since I like to use two font families—one for headings and another for paragraphs—I add the following to my tailwind.css file.
Alternatively, if you prefer to override the TailwindCSS configuration file and apply fonts directly to your HTML class attributes, you can configure the tailwind.config.ts file as follows:
You can then apply the fonts to your HTML class attributes.
Whichever way you decide to configure the fonts, you will achieve your desired result.
As I continue my journey to discover whether Remix.js is the right fit for me, I will keep writing about any interesting things I encounter. Hopefully, this will help someone else transitioning away from Next.js.