Issue
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
.
Solution
I have solved the issue by creating a component which contains the font face styles in an inline style appended to the <head>
with the help of Head
from next/head
. This way, I can utilize the getAssetUrl()
function based on the correct asset URL.
import Head from 'next/head';
import React from 'react';
import { getAssetUrl } from '../lib/assets';
export default function FontFaces() {
return (
<Head>
<style
dangerouslySetInnerHTML={{
__html: `
@font-face {
font-family: 'MyCustomFont';
font-style: normal;
font-weight: 400;
src: url('${getAssetUrl('fonts/MyCustomFont-Regular.ttf')}') format('truetype');
font-display: swap;
}
@font-face {
font-family: 'MyCustomFont';
font-style: normal;
font-weight: 700;
src: url('${getAssetUrl('fonts/MyCustomFont-Bold.ttf')}') format('truetype');
font-display: swap;
}
@font-face {
font-family: 'MyCustomFont';
font-style: italic;
font-weight: 700;
src: url('${getAssetUrl('fonts/MyCustomFont-BoldItalic.ttf')}') format('truetype');
font-display: swap;
}
`,
}}
/>
</Head>
);
}
Answered By - unspeakable29
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.