getOgImageUrl()
Use getOgImageUrl() to build the absolute OG image URL for a page from Nitro code, such as server routes and middleware. You don't need a Nuxt app context.
server/api/og-image.get.ts
import { defineEventHandler } from 'nuxt/server'
import { getOgImageUrl } from '#og-image/server'
export default defineEventHandler((event) => {
const url = getOgImageUrl(event, '/blog/hello', {
component: 'OgImagePost',
props: { title: 'My post' },
})
return { url }
})Syntax
import type { RequestEvent } from 'nuxt/server'
function getOgImageUrl(event: RequestEvent, options?: Partial<OgImageOptions>): string
function getOgImageUrl(event: RequestEvent, pagePath: string, options?: Partial<OgImageOptions>): stringevent: The current NuxtRequestEvent. Always pass it. On Cloudflare Workers,NUXT_APP_SECRETis an env binding, and env bindings resolve only through the event.pagePath: The page to build the URL for, for example/blog/hello. If you omit it, the current request path is used, without the appbaseURLor query.options: The same options asdefineOgImage(). If you omitcomponent, the first OG image component in your project is used.
Unless signing is disabled, the URL is a signed /_og/d/ URL. The signing secret derives from Nuxt appSecret, configured through NUXT_APP_SECRET.
The origin matches the page's og:image: your site URL, or the request origin if you have not set one.
Omitting the page path
In an API route, always pass
pagePath. The request path there is the API route, so getOgImageUrl(event) in server/api/og-image.get.ts builds an image for /api/og-image.In server middleware, skip requests that are not pages, such as assets and the /_og/ image requests:
server/middleware/og-image.ts
import { defineEventHandler, getRequestHeader } from 'nuxt/server'
import { getOgImageUrl } from '#og-image/server'
export default defineEventHandler((event) => {
if (!getRequestHeader(event, 'accept')?.includes('text/html'))
return
// read later in your own server code, for example a Nitro render hook
event.context.ogImageUrl = getOgImageUrl(event, { props: { title: 'My page' } })
})Was this page helpful?