vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.44k stars 27.04k forks source link

Error 'Failed to fetch `Noto Sans JP` from Google Fonts.' #45080

Closed max-ch9i closed 1 year ago

max-ch9i commented 1 year ago

Verify canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: Ubuntu 20.04.0 LTS Fri Jan 20 2023 09:56:57 GMT+0000 (Greenwich Mean Time)
Binaries:
  Node: 16.14.2
  npm: 7.17.0
  Yarn: 1.22.19
  pnpm: 7.13.6
Relevant packages:
  next: 13.1.3
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

Font optimization (@next/font)

Link to the code that reproduces this issue

https://stackblitz.com/edit/nextjs-qcjltu?file=app%2Fpage.js,package.json

To Reproduce

To reproduce, run npm run build.

Describe the Bug

Font input is

import { Noto_Sans_JP } from '@next/font/google';

const notoSansJapanese = Noto_Sans_JP({
  weight: '400',
  preload: false,
});

results in

Failed to compile.

app/page.js
`@next/font` error:
Failed to fetch `Noto Sans JP` from Google Fonts.

Possibly related to https://github.com/vercel/next.js/pull/44594 and https://github.com/vercel/next.js/commit/5f2c9d0b301588cec60c3bfb6b36cb7ece787659

Expected Behavior

Compiles successfully.

louistiti commented 1 year ago

I have the same issue with next@13.4.3 (current latest) and Node.js 18.16.0 (current LTS).

I'm currently based in China and use a VPN. I suppose that the fetching from the next/font package is failing because of that. Even though I successfully can reach the fetching URL (in my case: https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300;400;600;700;900&display=swap) from the browser. It works well once built and started. It only does not work when running the development server.

As a temporary fix I directly imported the Google stylesheet and removed the config related to next/font. Also, I deleted the .next folder and rerun the development server via npm run dev.

It is not ideal, but will do for now. Hope the team will take a closer look at the issue :pray:

Before

app/layout.tsx

import './styles/main.sass'
import { Source_Sans_Pro } from 'next/font/google'

const sourceSansPro = Source_Sans_Pro({
  weight: ['200', '300', '400', '600', '700', '900'],
  subsets: ['latin']
})

export const metadata = {
  title: 'Aurora - Leon\'s UI bricks',
  description: 'Aurora - Leon\'s UI bricks',
}

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

After

app/layout.tsx

import './styles/main.sass'

export const metadata = {
  title: 'Aurora - Leon\'s UI bricks',
  description: 'Aurora - Leon\'s UI bricks',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <head>
        <link
          href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@200;300;400;600;700;900&display=swap"
          rel="stylesheet"
        />
      </head>
      <body>{children}</body>
    </html>
  )
}

Hope that helps.

smorimoto commented 1 year ago

GitHub Actions often have network issues on GitHub hosted runners, so I published an action to address that. I don't expect that to reduce the failure rate to completely zero, but the rate should drop significantly. https://github.com/smorimoto/tune-github-hosted-runner-network

azzazkhan commented 1 year ago

Using Node v16.20.0 and Nex.js v13.4.4 but still facing issue Error [NextFontError]: Failed to fetch font Sofia Sans. I even tried the NODE_TLS_REJECT_UNAUTHORIZED=0 option but it didn't helped.

crobley commented 1 year ago

Maybe unrelated, but it could help someone.

I use Docker with WSL2 - I found if I turned off the "Add the *docker.internals names..." option in Docker desktop, it worked again.

image

Dev1OptimusTecno commented 1 year ago

Same here using Roboto-flex after updating next it had this error

hkmute commented 1 year ago

It appears to me that it is caused by issue in node-fetch when there are a large amount of font files to fetch.

node-fetch/node-fetch#1735

I have a font config requiring me to download 404 font files which makes it impossible for me to build the project successfully. The error is gone when I reduce the files required to 101.

The code below is fetching all the font files at nearly the same time. I can build successfully with 404 font files after I changed Promise.all to fetching sequentially.

https://github.com/vercel/next.js/blob/22ea7d99095cee37b327c5c674a78d893b95d38c/packages/font/src/google/loader.ts#LL106C1-L140C6

Hope nextjs team can consider batching the requests here to avoid this issue

exipnus commented 1 year ago

Hello,

Any news on this? I still have this issue on next v13.4.4. I am on node v18.16.0 I have also deleted the .next folder. The error I get is:

AbortError: The user aborted a request.
    at abort (/home/user/code/projects/my-project.com/web/node_modules/next/dist/compiled/node-fetch/index.js:1:65190)
    at EventTarget.abortAndFinalize (/home/user/code/projects/my-project.com/web/node_modules/next/dist/compiled/node-fetch/index.js:1:65410)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:737:20)
    at EventTarget.dispatchEvent (node:internal/event_target:679:26)
    at abortSignal (node:internal/abort_controller:314:10)
    at AbortController.abort (node:internal/abort_controller:344:5)
    at Timeout.<anonymous> (/home/user/code/projects/my-project.com/web/node_modules/next/dist/compiled/@next/font/dist/google/fetch-font-file.js:24:51)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7) {
  type: 'aborted'
}
ben-aggus-gateway commented 1 year ago

Same issue/error as directly above while running local. Running on Windows 10 environment if that matters. Node V 18.16.0, Next 13.2.4

VityaSchel commented 1 year ago

Getting sometimes in docker

Errytagedesign commented 1 year ago
preload: false,

I just encounter the same issues with version 13.4.5 and I added this solution preload: false and it works fine for me. I'm using a Mac, Nodejs v16.15.1, Hope this helps anyone facing the same issues

hamedor commented 1 year ago

Im located in Russia and got this error. Fixed by using VPN.

akangaziz commented 1 year ago

Im located in Russia and got this error. Fixed by using VPN.

works for me. thanks :)

johansunden commented 1 year ago

I have this issue too when I run the app in my local environment. I didn't notice the issue for a while I think, so maybe there are others who haven't realised that there is an issue. I've only seen the message that the font failed to fetch once in my terminal (not sure what I did to see it), but today and yesterday it happens every time I run npm run dev., though I don't see any message that it failed to fetch the font (Poppins in my case). Basically it's like this:

If I run npm run dev, when I inspect some text in the browser the font is: font-family: '__Poppins_Fallback_4467c8','__Poppins_Fallback_Fallback_4467c8';

If I run npm run build + npm run start, when I inspect some text in the browser the font is: font-family: __Poppins_6536b5, __Poppins_Fallback_6536b5;

So in the npm run dev scenario it uses a fallback font, and I didn't even realise until I tried to use font weight 500 on a text and it was not difference from 400 when it was using the fallback font.

tonyjara commented 1 year ago

I had the same issue and solved it by deleting my .next folder and switching to a different wifi. I have a very slow connection in some places, maybe it timed out because of that.

2manoj1 commented 1 year ago

Same issue in WSL ubuntu after upgrade also. Any fix?

Rashmi-278 commented 1 year ago

For me, unstable internet connection was the issue, it didn't work locally but build passes on Vercel deployments

dantevicenzo commented 1 year ago

Here is how i managed to fix:

  1. run nvm install --lts
  2. run nvm use --lts
  3. delete .next folder

Done. Now i can run npm run dev without any errors.

shuding commented 1 year ago

This issue will be fixed #51890. We now have retry logic when this fails, CLI errors that tell you about unstable network, and it's no longer depending on AbortController.

Let us know if you have other suggestions!

thekidnamedkd commented 1 year ago
Windows 10: WSL 2 -- Unbuntu 20.04
Node: 16.15.0
npm: 8.5.5
Next: 13.2.4 

I have a pretty reasonable connection, but would continually get this error in development. This seems to be an issue with the size of the fonts you want to use as I was having no problem with IBM-Plex-Mono at ~136kb per weight and lots of problems with Dongle at ~4775kb per weight, according to local file sizes after downloading from Google Fonts. Reconfigured to have Dongle in styles/fonts/ using localFont import from next/fonts/local in 'lib/fonts.ts' after much frustration and inconsistency using the next/fonts/google import and seems to be resolved. Here is my working code with Tailwind CSS vars:

lib/fonts.ts

import { IBM_Plex_Mono } from 'next/font/google';
import localFont from 'next/font/local';

export const plexmono = IBM_Plex_Mono({
  subsets: ['latin'],
  weight: ['100', '200', '300', '400', '500', '600', '700'],
  variable: '--font-plexmono',
});

export const dongle = localFont({
  src: [
    {
      path: '../styles/fonts/Dongle-Light.ttf',
      weight: '300',
      style: 'thin',
    },
    {
      path: '../styles/fonts/Dongle-Regular.ttf',
      weight: '400',
      style: 'normal',
    },
    {
      path: '../styles/fonts/Dongle-Bold.ttf',
      weight: '700',
      style: 'bold',
    },
  ],
  variable: '--font-dongle',
});

pages/_app.tsx

. . . 
<main className={`${dongle.variable} ${plexmono.variable}`}>
     <Layout>
            <Component {...pageProps} />
     </Layout>
</main>
. . . 

tailwind.config.js


theme: {
. . .
    },
    extend: {
      fontFamily: {
        body: ['var(--font-plexmono)'],
        heading: ['var(--font-dongle)'],
      },
. . .
}
francisceril commented 1 year ago

Was this ever solved?

This is hit and miss for me. Sometimes it just works then all of a sudden it doesn't work. Happens regardless of what font I use or what network I'm on.

If it may help. node: 18.16.0 next: 13.4.10

SehajBindra commented 1 year ago
import { Poppins } from "next/font/google";

const poppins = Poppins({
  weight: ["300", "400", "500", "600", "700"],
  subsets: ["latin"],
  preload: false,
  style: ["normal"],

  display: "swap",
});`  

### for me, this worked set preload:false

khalidmesbah commented 1 year ago

this answer worked for me https://stackoverflow.com/questions/76478043/next-js-always-fail-at-downloading-fonts-from-google-fonts

qnrjs42 commented 1 year ago

a temporary expedient

// in _app.tsx

/* eslint-disable react/no-unknown-property */

/* eslint-disable camelcase */
import { useTranslation } from 'next-i18next';
import { Noto_Sans_KR, Inter } from 'next/font/google';
import Head from 'next/head';

import type { LocaleType } from '@interfaces/default';

const notosansKR = Noto_Sans_KR({
  weight: ['100', '300', '400', '500', '700', '900'],
  display: 'auto',
  subsets: ['latin'],
  style: 'normal',
  variable: '--noto-sans_KR',
  preload: true,
});

const inter = Inter({
  weight: ['400', '700', '800'],
  subsets: ['latin'],
  display: 'fallback',
  fallback: ['-apple-system', 'sans-serif'],
});

const GlobalFont = ({ children }: { children: React.ReactNode }) => {
  const { i18n } = useTranslation('');

  const renderFontLink = (currentLocale: LocaleType): JSX.Element | null => {
    switch (currentLocale) {
      case 'ja':
        return (
          <link
            rel='stylesheet'
            href='https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100;300;400;500;700;900&display=swap'
          />
        );
      default:
        return null;
    }
  };

  return (
    <>
      <Head>
        <link rel='preconnect' href='https://fonts.googleapis.com' />
        <link rel='preconnect' href='https://fonts.gstatic.com' crossOrigin='' />

        {renderFontLink(i18n.language)}
      </Head>

      {process.env.NODE_ENV !== 'development' ? (
        <style jsx global>
          {`
            body {
              font-family: ${notosansKR.style.fontFamily}, 'Noto Sans JP', -apple-system, sans-serif;
            }

            .inter-font {
              font-family: ${inter.style.fontFamily};
            }
          `}
        </style>
      ) : null}

      {children}
    </>
  );
};

export default GlobalFont;
// in _app.tsx

import { css, Global } from '@emotion/react';

const GlobalStyles = (
  <Global
    styles={css`
      * {
        font-family: ${process.env.NODE_ENV === 'development'
          ? "'Noto Sans KR', 'Noto Sans JP', -apple-system, sans-serif;"
          : ''};
      }
      .inter-font {
        font-family: ${process.env.NODE_ENV === 'development'
          ? "'Inter', 'Noto Sans KR', sans-serif;"
          : ''};
      }
    `}
  />
);

export default GlobalStyles;

But, There is an issue with warnings in the browser console.

Do not add stylesheets using next/head (see <link rel="stylesheet"> tag with href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100;300;400;500;700;900&display=swap"). Use Document instead.

adbutterfield commented 1 year ago

Tangential to the original issue, but I made a package that nice when you need to work with Japanese fonts: https://www.npmjs.com/package/react-content-font

Ianduha13 commented 1 year ago

Sorry if anyone already mentioned it but i found an interesting workaround trying to solve this problem:

import { Red_Hat_Display as redHatDisplay } from 'next/font/google'

Using the as keyword to rename the font I can forget about the issue

Joblyn commented 1 year ago

This issue will be fixed #51890. We now have retry logic when this fails, CLI errors that tell you about unstable network, and it's no longer depending on AbortController.

Let us know if you have other suggestions!

@SehajBindra this error still persists with Poppins font. I'm using next 13.4.10

----layout.tsx----

import './globals.scss'
import type { Metadata } from 'next'
import { Poppins } from 'next/font/google'

const poppins = Poppins({
  display: 'swap',
  weight: ['300', '400', '500', '700'],
  style: ['normal'],
  subsets: ['latin']
})

export const metadata: Metadata = {
  title: 'Xchange Next Door',
  description: 'Xchange Next Door'
}

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

----error----

error Failed to download 'Poppins' from Google Fonts. Using fallback font instead.
AbortError: The user aborted a request.

----package.json----

{
 ...
 "dependencies": {
   "@types/node": "20.4.2",
    "@types/react": "18.2.15",
    "@types/react-dom": "18.2.7",
    "autoprefixer": "10.4.14",
    "eslint": "8.45.0",
    "eslint-config-next": "13.4.10",
    "next": "13.4.10",
    "postcss": "8.4.26",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "styled-components": "^6.0.4",
    "swiper": "^10.0.4",
    "tailwind-scrollbar": "^3.0.4",
    "tailwindcss": "3.3.3",
    "typescript": "5.1.6"
 }
 ...
}
nekofar commented 1 year ago

I've encountered issues with different fonts bearing various names. This situation has been disrupting my development and continuous integration (CI) workflows. Despite the passage of several months, the most reliable solution I've found is to download the fonts and utilize them locally through next/font/local. 😞

SehajBindra commented 1 year ago

This issue will be fixed #51890. We now have retry logic when this fails, CLI errors that tell you about unstable network, and it's no longer depending on AbortController. Let us know if you have other suggestions!

@SehajBindra this error still persists with Poppins font. I'm using next 13.4.10

----layout.tsx----

import './globals.scss'
import type { Metadata } from 'next'
import { Poppins } from 'next/font/google'

const poppins = Poppins({
  display: 'swap',
  weight: ['300', '400', '500', '700'],
  style: ['normal'],
  subsets: ['latin']
})

export const metadata: Metadata = {
  title: 'Xchange Next Door',
  description: 'Xchange Next Door'
}

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

----error----

error Failed to download 'Poppins' from Google Fonts. Using fallback font instead.
AbortError: The user aborted a request.

----package.json----

{
 ...
 "dependencies": {
   "@types/node": "20.4.2",
    "@types/react": "18.2.15",
    "@types/react-dom": "18.2.7",
    "autoprefixer": "10.4.14",
    "eslint": "8.45.0",
    "eslint-config-next": "13.4.10",
    "next": "13.4.10",
    "postcss": "8.4.26",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "styled-components": "^6.0.4",
    "swiper": "^10.0.4",
    "tailwind-scrollbar": "^3.0.4",
    "tailwindcss": "3.3.3",
    "typescript": "5.1.6"
 }
 ...
}

So Next js 13.4.13 recommends variable fonts for better optimization so after reading the the documentation I got the solution so in Poppins font weight prop is required and subsets is required when preload is set to true. So in weight prop you can only add two weight sizes as weight: '100 900' for a variable font.

for further check out the docs : https://nextjs.org/docs/pages/api-reference/components/font

This worked for me !!

const poppins = Poppins({
  weight: ["400", "700"],
  subsets: ["latin"],
});
KrustyC commented 1 year ago

I keep experiencing this issue very intermittently. SOmetimes it loads all fonts, sometimes none, and sometimes only one (I am using 4 different fonts). I initially thought this was due to bad connectivity but I am experiencing this on a decent connection (>40Mbps) so I am sure that can not be the issue.

When I build the app on Vercel I get no issues so it is working fine in production, but in dev it makes it very difficult to work with, because everything looks ugly as it falls back to the default font.

For context I keep on seeing the following message

AbortError: The user aborted a request.
    at abort (/Users/{MAC_USER}/repos/sites/thescrapbookers.blog/node_modules/next/dist/compiled/node-fetch/index.js:1:65190)
    at EventTarget.abortAndFinalize (/Users/{MAC_USER}/repos/sites/thescrapbookers.blog/node_modules/next/dist/compiled/node-fetch/index.js:1:65410)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:731:20)
    at EventTarget.dispatchEvent (node:internal/event_target:673:26)
    at abortSignal (node:internal/abort_controller:308:10)
    at AbortController.abort (node:internal/abort_controller:338:5)
    at Timeout.<anonymous> (/Users/{MAC_USER}/repos/sites/thescrapbookers.blog/node_modules/next/dist/compiled/@next/font/dist/google/fetch-font-file.js:24:51)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  type: 'aborted'
}
javierdev0 commented 1 year ago

I changed the node version, removed the .next folder and it worked.

My recommendation is to look if you have several versions of node installed and make sure you use the correct version, in this case for me version 18.12.1 worked.

My problem was that when I did node -v in the console, it printed the latest version installed on my computer but when I did an nvm ls, I realized that I was actually using another version and not the latest.

Before Captura de pantalla 2023-08-16 155359

After Captura de pantalla 2023-08-16 155455

gidgudgod commented 1 year ago

restarting my internet connection (wi-fi) and deleting .next folder worked for me

github-actions[bot] commented 1 year ago

This closed issue has been automatically locked because it had no new activity for 2 weeks. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.