Home > Blockchain >  Browser cannot get woff font file using @font-face
Browser cannot get woff font file using @font-face

Time:11-23

For my server I wish to enable dynamic loading of fonts. The server runs with nestjs

I host the .woff files in a directory on the server named 'fonts'.

The @font-face is constructed dynamically (according to desired fonts) in a style tag in the html's head section.

However, when I set the url to the file's path, like this:

@font-face {
      font-family: Roboto;
      src: url(fonts/roboto-v29-latin-regular.woff);
    }

then the GET ends with 404 not found.

When I simply use the file's name:

@font-face {
          font-family: Roboto;
          src: url(roboto-v29-latin-regular.woff);
        }

then an empty object is returned {}

Would appreciate your insights!

CodePudding user response:

The problem was that nestjs did not serve the font files. I had to serve them statically from the appModule using ServeStaticModule.forRoot:

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'fonts'),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})

then copy my fonts folder to the dist directory. This fixed the problem.

CodePudding user response:

There are a couple of solutions that could be potential fixes, depends on how you handle your CSS files.

If you have the roboto-v29-latin-regular.woff file inside fonts folder, it means that CSS tries to find the path in the local directory. To find something in the local directory use dot in front of the slash ( ./ ). So if we have the following directory:

/fonts
 -roboto-v29-latin-regular.woff
styles.css

Then the path for roboto-v29-latin-regular.woff would be ./fonts/roboto-v29-latin-regular.woff and it would result in the following font-face:

@font-face {
  font-family: Roboto;
  src: url(./fonts/roboto-v29-latin-regular.woff);
}

This is how you can easily access local or directories above the current level you are on. Read this.

However if you process CSS differently, you have to provide only one / in front of the fonts folder which would result from font fetching from the local instance server URL:

/* Imagine your URL to be: http://localhost:3000/fonts/roboto-v29-latin-regular.woff */

@font-face {
  font-family: Roboto;
  src: url(/fonts/roboto-v29-latin-regular.woff);
}

Again if none of the solutions above work just place the font external URL ( from google fonts etc. )


@font-face {
  font-family: Roboto;
  src: url(<EXTERNAL_URL>);
}
  • Related