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

Tips for concurrently and asynchronously executing multiple AJAX requests

I am working with a javascript object named Agendamento which includes the following key parts: const Agendamento = { // ... storeResultados: async function (consulta) { //... $.ajax({ type: 'POST', ...

A beginner's guide to using Jasmine to test $http requests in AngularJS

I'm struggling with testing the data received from an $http request in my controller as I don't have much experience with Angular. Whenever I try to access $scope, it always comes back as undefined. Additionally, fetching the data from the test ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

Unable to minimize or hide the ace editor widget with Cypress

Today marks the beginning of my journey into posting on this platform, and I am eager to get it right. In my current project using Cypress for writing integration tests, I encountered a challenge while attempting to click on an Ace editor widget within a ...

Issue with jQuery selector not updating when variable changes

'I am attempting to create a functionality where a function is triggered upon clicking the "hit" class, but only when the correct parent "box" id is selected. var currentSelection = 1; $('#box-' + currentSelection + ' .hit'). ...

``Is there a specific scenario where the use of getInitialProps is recommended when automatically redirecting from one

Within my application, I have set up an auto-redirect from the root directory '/' to '/PageOne' with the following code: const Home = () => { const router = useRouter(); useEffect(() => { router.push('/pageone', ...

Do not use npm to install underscore libraries

How can I resolve the error I encountered while attempting to install packages using npm? Here is my packages file: "dependencies": { "express": "~3.3.6", "socket.io": "0.9.16", "jade": "~0.35.0", "less-middleware": "~0.1.12", "redis ...

Easily fetching data with AJAX through jQuery

Completely new to using jQuery and AJAX, I attempted the code below for a simple http get request: <html> <head> </head> <body> <script src = "jquery-2.1.4.js"></script> <script src = "app.js"></script& ...

Utilize a method in Vue.js to filter an array within a computed property

I have a question regarding my computed property setup. I want to filter the list of courses displayed when a user clicks a button that triggers the courseFilters() method, showing only non-archived courses. Below is my current computed property implement ...

Ajax - Retrieving data from a different webpage

My index.php contains the following HTML: <div id="showDetails"> </div> <div id="showList"> </div> And this Ajax function is also in index.php: function ...

ASP.NET MVC - AjaxContext is a powerful feature provided by the

I recently attempted to delve into the AjaxContext utilized by ASP.NET-MVC in scenarios such as Ajax Actionlinks and their clientside functions like onSuccess and onComplete. However, I must admit that I found it quite confusing... Is there any documentati ...

The console indicates that the state's arrays have been filled, yet I'm unable to retrieve the object[0]

In my code, the functions that populate the state are called on component will mount. When I log the state on the render, this is what I observe in the log. The log clearly shows that the arrays in the state have been populated, although there seems to be ...

Can you explain the roles of client-side and server-side in Next.js?

Could someone please elaborate on the distinction between client side and server side in Next.js as detailed in their documentation? As far as I understand, Next.js operates on React which is client side and runs in the browser, while server side refers to ...

Utilizing the validator in Vue with the setup script, TypeScript, and the composition API

While working on some code from a tutorial, I came across the challenge of implementing a validator in a similar fashion to the example provided. My task involves utilizing the script setup, typescript, and the composition API. props: { image: { ...

Exchange one HTML element with a different HTML element

I've been attempting to change an HTML tag using PHP or jQuery. The current default tag is: <li class="dropdown"> <a href="index.html" class="dropdown-toggle"> Home</a></li> My desired replacement for the above HTML tag is: ...

Is the NEXTAUTH_SECRET variable equivalent to the backend secret utilized for JWT token generation?

In my current project, I am developing the frontend application using NextJS and incorporating next auth for user authentication with email and password login. The backend is implemented in GoLang as a separate code base. When a user logs in, a request is ...

Guide on Minimizing ES6 with Gulp

I am new to creating a gulpfile.js manually for my project based on Backbone and Marionette. My initial gulp file had the following structure: var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var browserify = require ...

The issue arises when trying to call a JavaScript function that has not been properly

Initially, write code in resources/js/app.js file function button1Clicked(){ console.log('Button 1 is clicked'); } Next, include the following code in testing.blade.php file <!DOCTYPE html> <html> <head> <meta name="cs ...

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

The application of the Same Origin Policy appears to be ambiguous when utilizing the jQuery AJAX

I'm exploring the application of the Same Origin Policy (SOP) in various scenarios. Here is some JavaScript code that I have written in a local HTML file and executed using Chrome on Windows: $(document).ready(function () { $.get("http://www.qu ...