Fonts
You can serve fonts from both Google Fonts and local sources by including the Google Fonts link in your document.js and using the @font-face CSS rule to declare local font files.
Local Fonts
Adding local fonts to a project involves following steps:
- To add local fonts to your project, place the font files in a
src/static/fontsdirectory within your project. - Use the @font-face CSS rule to declare font-face rules, specifying the font family and source file paths inside
src/static/css/base/index.scssdirectory.
src/static/css/base/index.scss
@import "styles";
@font-face {
font-family: Poppins;
font-style: normal;
font-weight: 700;
font-display: optional;
src: local("Poppins Bold"), local("Poppins-Bold"),
url($font_url + "Poppins-Bold-Subset.woff2") format("woff2");
unicode-range: U+0020-007F, U+201C, U+201D, U+00A;
}
- To serve a static font file in Express, use the express.static middleware to specify the directory containing your font files. For example:
server/server.js
const express = require("express")
const path = require("path")
// Server middlewares are added here.
export function addMiddlewares(app) {
app.use("/favicon.ico", express.static(path.join(__dirname, "../public/favicon.ico")))
app.use("/assets", express.static(path.join(__dirname, `./src/static/fonts`)),)
}
This assumes your font files are stored in the src/static/fonts directory.
Google Fonts
For Google Fonts, simply include the link provided by Google Fonts in the head section of your document.js file under server, specifying the desired font families in your CSS using the font-family property.
server/document.js
import React from "react"
import { Head, Body } from "catalyst-core"
function Document(props) {
return (
<html lang="en">
<Head {...props}>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="" />
<link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet" />
</Head>
<Body {...props} />
</html>
)
}
export default Document