Search IconIcon to open search

Search

Using local Google Fonts in Hugo

written by: Moritz Vogel

Last updated Feb 28, 2023

As I was customizing this blog, I wanted to change the fonts to fit the style of my Website. I used three different Fonts there:

To comply to local law I needed to host the Google Fonts by myself, so I needed to do this again for this blog. Google explains how you can do this in this blog post. But you basically just download the font that is referenced in the stylesheet and change that reference to a local path.

# Problem

So I downloaded the fonts and put them in the asset folder, like I would normally do in frameworks like vue.js. But after I pushed my changes to GitHub pages, the fonts were not available in the specified path.

# Solution

Because hugo uses a webpacker the paths from the development environment do not exist any more, but I noticed that files from the static/ folder seem to be in the root directory of the compiled version of the project.

So I moved my fonts into static/fonts and referenced the fonts with fonts/<FONT_NAME>

# Example

To reference the DM Serif Display font for example, you need to add the following to the assets/styles/custom.scss:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* latin-ext */
@font-face {
  font-family: 'DM Serif Display';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: url(/fonts/-nFnOHM81r4j6k0gjAW3mujVU2B2G_5x0ujy.woff2) format('woff2');
  unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}

/* latin */
@font-face {
	font-family: 'DM Serif Display';
	font-style: normal;
	font-weight: 400;
	font-display: swap;
	src: url(/fonts/-nFnOHM81r4j6k0gjAW3mujVU2B2G_Bx0g.woff2) format('woff2');
	unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

:root {
	--font-body: "Roboto Serif";
	--font-header: "DM Serif Display";
	--font-mono: "Red Hat Mono"
}

As you can see the relative path does not correspond to the folder structure of your development environment! The path changes after it is compiled by the webpacker