'How to use custom fonts on a Next.js app under a sub-path of a domain?

I have a Next.js app deployed under a sub-path of a domain (e.g. example.com/my-next-js-app). For the bundle scripts and styles, I was able to resolve them using Next.js config:

const isProd = process.env.NODE_ENV === 'production';
module.exports = {
  basePath: isProd ? '/my-next-js-app' : '',
};

For images, I'm able to create a function that will add a prefix to the image url if it's on production env.

export function getAssetUrl(path: string) {
  return process.env.NODE_ENV === 'production' ? `${MAIN_URL}${path}` : path;
}

But for the fonts, I'm not quite sure what is the recommended way. Currently I have custom font faces in my styles/globals.css as below:

@font-face {
  font-family: 'MyCustomFont';
  font-style: normal;
  font-weight: 400;
  src: url('/fonts/MyCustomFont-Regular.ttf') format('truetype');
  font-display: swap;
}

@font-face {
  font-family: 'MyCustomFont';
  font-style: normal;
  font-weight: 700;
  src: url('/fonts/MyCustomFont-Bold.ttf') format('truetype');
  font-display: swap;
}

@font-face {
  font-family: 'MyCustomFont';
  font-style: italic;
  font-weight: 700;
  src: url('/fonts/MyCustomFont-BoldItalic.ttf') format('truetype');
  font-display: swap;
}

So when deployed, fonts will not be in the root public folder but it will be in example.com/my-next-js-app/fonts/MyCustomFont-xxx.ttf.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source