Skip to content

Commit

Permalink
add node example to open graph image docs (#64305)
Browse files Browse the repository at this point in the history
### What?

Adds a Node.js example for using assets with `ImageResponse` to create
og images.

### Why?

The only examples available use `new URL` and `fetch` which does not
work when the runtime is using Node.js.

---------

Co-authored-by: Delba de Oliveira <[email protected]>
  • Loading branch information
souporserious and delbaoliveira authored Apr 18, 2024
1 parent 3966181 commit 843332f
Showing 1 changed file with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,65 @@ 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.
```jsx filename="app/opengraph-image.js" switcher
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'

export const runtime = 'edge'

export async function GET() {
const logoSrc = await fetch(new URL('./logo.png', import.meta.url)).then(
(res) => res.arrayBuffer()
)

return new ImageResponse(
(
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img src={logoSrc} height="100" />
</div>
)
)
}
```
#### 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.
```jsx filename="app/opengraph-image.js" switcher
import { ImageResponse } from 'next/og'
import { readFile } from 'node:fs/promises'

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

return new ImageResponse(
(
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<img src={logoSrc} height="100" />
</div>
)
)
}
```
## Version History
| Version | Changes |
Expand Down

0 comments on commit 843332f

Please sign in to comment.