Downloading fonts from Google Fonts is always a struggle when using Next.js

After initializing a fresh Next.js project using create-next-app, I managed to successfully launch it with npm run dev.

However, an issue arises every time Next.js boots up, displaying the following error:

FetchError: request to https://fonts.gstatic.com/s/inter/v12/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa1ZL7W0Q5nw.woff2 failed, reason: 
    at ClientRequest.<anonymous> (C:\Users\user\Desktop\documents\node_modules\next\dist\compiled\node-fetch\index.js:1:65756)
    at ClientRequest.emit (node:events:511:28)
    at TLSSocket.socketErrorListener (node:_http_client:495:9)
    at TLSSocket.emit (node:events:511:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ENETUNREACH',
  code: 'ENETUNREACH'
}
- error Failed to download `Inter` from Google Fonts. Using fallback font instead.

My main objective is to have Next.js utilize the specified font instead of resorting to a fallback option.

Strangely, this issue occurs even though I haven't made any alterations to the Next.js setup yet. Furthermore, accessing the URL

https://fonts.gstatic.com/s/inter/v12/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa1ZL7W0Q5nw.woff2
in my web browser functions smoothly, indicating that it's likely not a network-related problem.

I conducted a search through the Next.js documentation but didn't encounter any similar instances.

Here's the content of layout.tsx, located within src/app/:

import './globals.css'
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  )
}

Additionally, I am currently utilizing Node version 20.3.0, npm version 9.4.1, and Next.js version 13.4, all of which are the latest versions available at the time of composing this inquiry.

Answer №1

After trying out different browsers and clearing the cache without success, I finally found a solution. By adding the key display: 'swap', with the value swap, it resolved the issue:

This setting gives the font face an extremely small block period and an infinite swap period.

The "block" period for the font means:

If the font face isn't loaded, any element attempting to use it must render an invisible fallback font face. If the font successfully loads during this period, it is used as normal.

And the "swap" period for the font means:

If the font face isn't loaded, any element attempting to use it must render a fallback font face. If the font successfully loads during this period, it is used normally.

That's exactly what I needed to achieve.

Additionally, I included the key adjustFontFallback: false, which indicates:

A boolean value that determines whether an automatic fallback font should be used to reduce Cumulative Layout Shift. The default value is true.

So, here is my final version of layout.tsx:

import './globals.css'
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'], display: 'swap', adjustFontFallback: false})


export const metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  )
}

Answer №2

Encountered a similar problem with Bricolage Grotesque, but managed to fix it by implementing the following solution:

export const secondaryFont = Bricolage_Grotesque({
    subsets: ["latin"],
    variable: "--font-grotesque",
    display: "swap",
    adjustFontFallback: false,
});

Answer №3

In my scenario, the fonts were loading properly in the live environment where I have SSL set up.

Answer №4

Encountered the same issue, but managed to resolve it with a simple addition of display:"swap"

import { Montserrat } from "google-fonts-next";

const montserrat = Montserrat({
  weight: ["300", "400", "500"],
  subsets: ["latin"],
  display: "swap",
});

<body className={`${montserrat.className} ...`}> 
...
</body>

Answer №5

This updated version of Next resolved the problem I was facing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the window.scrollTop, ScrollY, or any other distance value while utilizing CSS scroll snap can be achieved by following these

I am currently utilizing css scroll snap for smooth scrolling through sections that are 100vh in height. The functionality of the scroll snap is quite impressive. However, I need to find a way to determine the exact distance the user has scrolled down the ...

JSON to URN Converter: A tool for converting JSON references

Is there a way to convert URL references to JSON and back again programmatically? (include:(and:List((or:(urn:li:adTargetingFacet:locations:List(urn:li:geo:102221843)) ),(or:(urn:li:adTargetingFacet:skills:List(urn:li:skill:17)))))) Are there any JavaScri ...

Eliminate attributes from an object that are not defined within a specific type interface

I am trying to filter out properties from an object that are not defined in a specific type interface. Suppose I have the following interface: export interface CreateCustomerUserInput { fullname: string; email: string; } And this is my initial o ...

Determining whether a user is accessing a page through a URL or by navigating within the app using Next.js

I'm facing a small issue that needs to be resolved. Our application has a specific functionality requirement: When a user attempts to access the route / via URL, they should be redirected to /abc. However, if the user tries to access the rout ...

Is there a way to extract the content length from the raw DraftJS data?

I have a system where I am storing the data from my DraftJS editor in my database as a JSON string by passing it through convertToRaw(editorState.getCurrentContent()). For example, this is how the stored data looks like in the database: {"blocks": [{"key ...

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

JavaScript method overloading involves defining multiple functions with the same name

In my JavaScript code, I have implemented method overloading using the following approach: function somefunction() { //1st function } function somefunction(a) { //2nd function } function somefunction(a,b) { //3rd function } somefunction(); // ...

NodeJS application experiencing significant delays due to slow response times from MySQL database queries

Currently, I am in the process of learning about Node.js. Through utilizing Express and Node-Mysql, I have been able to effectively query my mysql database and return the outcomes as JSON to the client. However, there seems to be a significant delay. Eve ...

Automated web browser capture downloading feature

Currently, I am in the process of developing a tool to streamline tasks at my workplace. One feature we need is an aspx webpage where users can input information, then click on a submit button. When the submit button is clicked, a javascript download dialo ...

Learn how to call JavaScript code from an HTML file using Ajax

I am encountering an issue with my website. The index.html page contains JavaScript code that triggers an AJAX request to show the content of other.html inside a div in index.html. However, despite the other.html loading correctly, the JavaScript code wit ...

Encountering a Next.js TypeScript Build Error related to the Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' issue

`I am currently working on a project in Next Js using TypeScript. During the build process with npm run build, I encountered the following errors in the terminal: # Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' do ...

Apply an opacity setting of 0.5 to the specific segment representing 30% of the scrollable div

I have a scrollable container for displaying messages. I would like to apply an opacity of 0.5 to the content in the top 30% of the container, as shown in this image: https://i.stack.imgur.com/NHlBN.png. However, when I tried using a background div with a ...

What is the reason behind being limited to sending only 5 requests if I fail to heed the data event?

I've come across some related questions while researching this topic, such as Why is node.js only processing six requests at a time?. However, I am still struggling to fully grasp the specifics. Below is a breakdown of my scenario: Firstly, let&apos ...

Shifting successive elements in an array alternates

I have been working on a pick list component and have come up with the following layout https://i.stack.imgur.com/TnHAp.gif Whenever I try to move consecutive items, it keeps toggling between those two Here's a snippet of my code: moveDown(){ ...

By default, showcase the value of the first item in the list selected in a mat-selection-list on a separate component

In my project, I have two essential components: 1)list (which displays a list of customers) 2)detail (which shows the details of a selected customer) These components are designed to be reusable and are being utilized within another component called cus ...

Server side processes automatically converting boolean parameters in Axios get requests to strings

My code involves a JSON object being passed as parameters to the Axios GET API. Here is the JSON object: obj = { name: "device" value: true, } The Axios GET request is made with the above object like this - tableFilter = (obj) => { ...

Utilizing Angular2 to scan barcodes

Im looking to create an application in asp.net 5 / Angular2 and I am encountering an issue with scanning barcodes. This is the TypeScript code for my component: @Component({ selector: 'barcode-scanner', templateUrl: 'app/scan.html& ...

Value in Hook not updating after memoization of parent component

Let's consider this scenario: import * as React from "react"; const useMyHook = ({ element }: { element: HTMLElement | null }) => { React.useEffect(() => { if (element) { console.log("element in hook", element); ...

Steps to activate a single button within a deactivated fieldset

Is there a way to deactivate all elements within a Fieldset, while keeping certain buttons active? Check out this demo. <fieldset ng-disabled="true"> <legend>Personalia:</legend> Name: <input type="text"><br> Em ...

Adjusting slidesPerView based on screen size in Ionic: A step-by-step guide

Recently, I encountered an interesting challenge while working on my ionic project. I had successfully created a slider using ion-slides to display multiple products. Everything was working perfectly for the portrait view with 1.25 slides per view (slide ...