#custom font with imageresponse
1 messages · Page 1 of 1 (latest)
To use a custom font with ImageResponse in Next.js, you need to fetch the font file and convert it to an array buffer. Here's an example of how you can do this:
const fontData = await fetch(
new URL('../../assets/TYPEWR__.ttf', import.meta.url),
).then((res) => res.arrayBuffer());
return new ImageResponse(
(
<div
style={{
backgroundColor: 'white',
height: '100%',
width: '100%',
fontSize: 100,
fontFamily: '"Typewriter"',
paddingTop: '100px',
paddingLeft: '50px',
}}
>
Hello world!
</div>
),
{
width: 1200,
height: 630,
fonts: [
{
name: 'Typewriter',
data: fontData,
style: 'normal',
},
],
},
);
(Source: Vercel Docs (https://vercel.com/docs/functions/edge-functions/og-image-generation/og-image-examples))
The error you're encountering (TypeError: Cannot read properties of undefined (reading '260')) might be due to the font file not being found or not being loaded correctly. Make sure the font file is in the correct location and that the URL you're using to fetch it is correct.
If you're still encountering issues, it might be helpful to look at the discussion in this Github Issue (https://github.com/vercel/next.js/issues/48081). The users there encountered similar issues and shared their solutions and workarounds.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@slender sage kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
Hmm, I don't know enough to give you a confident answer yet. The error message you're seeing typically indicates that you're trying to access a property or method on an undefined object. In this case, it seems like the object you're trying to call .arrayBuffer() on is undefined.
This could potentially be due to the fetch request not returning the expected result. Make sure the URL you're passing to fetch() is correct and that the resource it points to is available.
If you're still having trouble, you might find it helpful to add some error handling to your fetch request to catch any potential issues, like so:
fetch(new URL('../../assets/TYPEWR__.ttf', import.meta.url))
.then((res) => {
if (!res.ok) {
throw new Error('Network response was not ok');
}
return res.arrayBuffer();
})
.then((fontData) => {
// Use fontData here...
})
.catch((error) => {
console.error('There has been a problem with your fetch operation:', error);
});