Adding Vercel og:image generation to Astro project with Edge function
In a previous blog post, I mentioned that I was using a Next.js project to run the @vercel/og
logic to generate my og:images for my blog posts.
This is now no longer needed, I figured out how to run this in my Astro blog project (this site ;-)).
A few changes were needed for this. The original code in my Next.js project looked like this:
As you can see, JSX code is being used to build up the output for my og:image.
Using JSX code inside an serverless/edge API function only works inside the /api
folder inside Next.js projects deployed to Vercel.
On other frameworks deployed to Vercel (like Astro), this is not possible.
When attempting this, I got error messages like the following: vc-file-system:api/og.js:25:8: ERROR: The JSX syntax extension is not currently enabled
.
So I had to find a way around using JSX inside the API function.
Luckily, the ImageResponse
function also allows for “React-elements-like” objects to be used.
Using the example provided on the link above, I created the following Edge API Route inside my Astro project:
Now, I want the API route to be picked up by Vercel.
By default the Astro build command will not pick up these API routes in the root directory (since they are part of the (vercel build command)[https://github.com/withastro/astro/issues/5451#issuecomment-1339720682]).
So to get this working in my use case, I switched to using the (Vercel CLI)[https://vercel.com/docs/cli] to build and deploy my project.
After installing the cli globally with npm i -g vercel
, I can run vercel build
to build my project locally, and run vercel deploy --prebuilt
afterwards to deploy the locally created build directly to Vercel.
I also opted to disable the automatic deployments on pushes to my git repository, since I’m doing the deployments through the CLI now.
Disabling the automatic deployments was done by adding a vercel.json
file in the root directory, containing the following:
Hopefully this helps other people wanting to use serverless/edge API functions in their Astro projects. Source code can be found on GitHub.