Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preview to main #61

Merged
merged 7 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const metadata: Metadata = {
// added this just to make the console message go away
metadataBase: process.env.VERCEL_URL
? new URL(`https://${process.env.VERCEL_URL}`)
: new URL(`http://localhost:${3000 ?? process.env.PORT}`),
: new URL(`http://localhost:${process.env.PORT ?? 3000}`),
title: {
template: '%s | chris.lu',
default: 'Home | chris.lu',
Expand Down
2 changes: 1 addition & 1 deletion app/web_development/og/[key]/opengraph-image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default async function OGImage(props: IImageProps) {

const baseUrl = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: `http://localhost:${3000 ?? process.env.PORT}`
: `http://localhost:${process.env.PORT ?? 3000}`

// Font
const permanentMarkerRegular = fetch(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Styling the navigation and using next/font - Tutorial
description: Styling the navigation and using next/font - Next.js static MDX blog | www.chris.lu Web development tutorials
keywords: ['navigation', 'Styling', 'next/font', 'nextjs', 'react']
published: 2024-08-20T16:16:16.444Z
modified: 2024-08-20T16:16:16.444Z
modified: 2024-09-12T16:16:16.444Z
permalink: https://chris.lu/web_development/tutorials/next-js-static-mdx-blog/navigation-styling-and-next-font
section: Web development
---
Expand Down Expand Up @@ -48,10 +48,22 @@ export const metadata = {

Now that our Navigation is working, we will add a few touches of color and use [next/font](https://nextjs.org/docs/app/api-reference/components/font) to add a custom web font to our project

## next/font to use an open source font

When using **next/font**, you can use any font available on [google fonts](https://fonts.google.com/) or use your own local font(s), the best part about using next/font is that it will optimize the loading of the font and make sure that there are zero layout shifts, also when using next/font we are self-hosting the font(s), which means we will NOT need to make an external network request to fetch the font, which will decrease loading times but also increase privacy as NO request is made to google servers

There is one optimization you can see when you deploy on vercel, Next.js will add a [link](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element, with the `rel` attribute set to `preload`, to your pages `<head>` element. This `<link>` will tell the browser to preload your font (which will decrease the loading time when getting the font):

```html
<link rel="preload" href="/_next/static/media/00000-s.p.woff2" as="font" crossorigin="" type="font/woff2">
```

> [!WARN]
> When I run the website in production mode locally (to run a production build locally you can use commands `npm run build` and then `npm run start`), I can NOT see the preload optimization (using Next.js 14.2.11). I'm not sure this is a bug, but I found the [Next.js Issue #62332](https://github.com/vercel/next.js/issues/62332) which seems to be related. I also tried Next.js 15 and there the problem seems to be fixed, I can even see the `<link>` element that preloads the font(s), when I run the project in development

> [!MORE]
> [Next.js "Font Optimization" chapter](https://nextjs.org/docs/pages/building-your-application/optimizing/fonts)

## next/font with an open source font

Because we are using the font for our navigation, let's start by editing our `layout.tsx` file (that is in the `app` folder) and import the font from there:

```tsx title="/app/layout.tsx" showLineNumbers {4} {11-16} {24} /className={kablammo.variable}/#special
Expand Down Expand Up @@ -107,6 +119,68 @@ Lines 11 to 16: we set some options for the font:

Line 24: we add the font style to our HTML element

> [!WARN]
> In the last chapter of the [Next.js "font optimization" documentation](https://nextjs.org/docs/app/building-your-application/optimizing/fonts#reusing-fonts), there is a very import information about how Next.js caches fonts at build time, quote:
>
> > Every time you call the localFont or Google font function, that font is hosted as one instance in your application. Therefore, if you load the same font function in multiple files, multiple instances of the same font are hosted.
>
> So if you have a font that you need in multiple pages it is probably best to load it in the layout and not load the same font in several different pages; have a look at the [Next.js "font optimization" documentation](https://nextjs.org/docs/app/building-your-application/optimizing/fonts#reusing-fonts) where they list several options you can use to avoid having multiple instances of the same font file in your Next.js cache; this is important because if you have multiple instances of the font it would mean that the browser will load the font multiple times, instead of just once

> [!MORE]
> [Next.js "next/font" documentation](https://nextjs.org/docs/app/api-reference/components/font)

### next/font with a local font (optional)

> [!NOTE]
> I'm not going to deep dive into this, but just know that if you prefer using a local font that you downloaded in the past, you can do that too using next/font

Here is a simple example of how to add a local font to our `layout.tsx` file:

```tsx title="/app/layout.tsx" showLineNumbers {4} {11-16} {24} /className={kablammo.variable}/#special
import './global.css'
import { Metadata } from 'next'
import HeaderNavigation from '@/components/header/Navigation'
import localFont from 'next/font/local'

export const metadata: Metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}

const myFont = localFont({
src: './assets/fonts/myFont.woff',
variable: '--font-myFont',
weight: ['400'],
display: 'swap',
})

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en" className={myFont.variable}>
<body>
<header>
<HeaderNavigation />
</header>
<main>{children}</main>
<footer>
<p>My Footer</p>
</footer>
</body>
</html>
)
}
```

Line 4: instead of importing a google font from next/font we are this time importing **localFont** function from next/font

Lines 11 to 16: we replace the previous code, with new code that uses the **localFont** function, the options we use are similar to those we used previously, the only difference is that we replace the **subsets** with an **src** option, as src you should set a value that is the path to the local font, assuming it is located inside of your `public` folder, so as our font has an src set to `./assets/fonts/myFont.woff` tells next/font that we have stored our local `myFont.woff` font file in `/public/assets/fonts`

Line 24: same as before, we add the font style to our HTML element

## Navigation CSS module

Next, we are going to add a stylesheet for our Navigation component and use the new font for the navigation items
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ import { SpeedInsights } from '@vercel/speed-insights/next'
export const metadata: Metadata = {
metadataBase: process.env.VERCEL_URL
? new URL(`https://${process.env.VERCEL_URL}`)
: new URL(`http://localhost:${3000 ?? process.env.PORT}`),
: new URL(`http://localhost:${process.env.PORT ?? 3000}`),
title: {
template: '%s | example.com',
default: 'Home | example.com',
Expand Down
4 changes: 2 additions & 2 deletions components/animated/Typing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ const Button: React.FC<IProps> = ({ children, colorChange, randomize }) => {
const characterIndexRef = useRef(0)
const pauseIndexRef = useRef(20)
const actionRef = useRef('type')
const withColorChange = true ?? colorChange
const randomizeColors = false ?? randomize
const withColorChange = colorChange ?? true
const randomizeColors = randomize ?? false

const [wordState, setWordState] = useState('')
const [colorState, setColorState] = useState<IColorGradient | null>(null)
Expand Down
2 changes: 1 addition & 1 deletion components/neonRoad/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const NeonRoadCanvas: React.FC<IProps> = (props) => {
//frameloop="never"
//onCreated={onCanvasCreatedHandler}
//ref={canvasRef}
camera={{} ?? cameraRef.current}
camera={cameraRef.current ?? {}}
>
{/*<Suspense fallback={<Loader />}>*/}
<PerspectiveCamera
Expand Down
Loading