Skip to content

Commit

Permalink
docs: update og generation code with local assets (#64888)
Browse files Browse the repository at this point in the history
### What?
This PR fixes OpenGraph generation code with local assets in Node.js
runtime. Also adds some notes on file location.

The updated code is validated with my project on vercel.

### Why?
I tried loading a file in `public` folder(say `./public/og.png`). The
Node.js local assets example code did work locally with `next start` but
failed with error message `Error: ENOENT: no such file or directory`
when deployed to vercel.

Then I found out the trick here is the relative path. On my local
machine the CWD is the root folder so the relative path works, And it
seems the CWD is somewhat different on vercel runtime. Then I tried
using `process.cwd()` to get the CWD and construct a absolute path, this
has been validated with my project on vercel.

Also it's worthy to note where the local assets should be placed, so
that devs could be less confused.

---------

Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
  • Loading branch information
3 people authored Apr 23, 2024
1 parent dd9324f commit 769a19e
Showing 1 changed file with 4 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ export default async function Image({ params }) {
#### Using Edge runtime with local assets
This example uses the Edge runtime to fetch a local image on the file system and passes it as an `ArrayBuffer` to the `src` attribute of an `<img>` element.
This example uses the Edge runtime to fetch a local image on the file system and passes it as an `ArrayBuffer` to the `src` attribute of an `<img>` element. The local asset should be placed relative to the example source file location.
```jsx filename="app/opengraph-image.js" switcher
import { ImageResponse } from 'next/og'
Expand Down Expand Up @@ -425,14 +425,15 @@ export async function GET() {
#### Using Node.js runtime with local assets
This example uses the Node.js runtime to fetch a local image on the file system and passes it as an `ArrayBuffer` to the `src` attribute of an `<img>` element.
This example uses the Node.js runtime to fetch a local image on the file system and passes it as an `ArrayBuffer` to the `src` attribute of an `<img>` element. The local asset should be placed relative to the root of your project, rather than the location of the example source file.
```jsx filename="app/opengraph-image.js" switcher
import { ImageResponse } from 'next/og'
import { join } from 'node:path'
import { readFile } from 'node:fs/promises'

export async function GET() {
const logoData = await readFile('./logo.png')
const logoData = await readFile(join(process.cwd(), 'logo.png'))
const logoSrc = Uint8Array.from(logoData).buffer

return new ImageResponse(
Expand Down

0 comments on commit 769a19e

Please sign in to comment.