Unverified Commit a3e56c9c authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Move ImageResponse to next/og (#56662)

### Story

Since we introduced `ImageResponse` into `next/server` export, there're a few libraries relying on `next/server` that accidentally ended up with bundling og image into the bundle. As og package is quite large that could easily raise the size concern for middleware, edge runtime routes.

### Struggles
 We've done optimizations. The tree-shaking strategies are tricky, we tried modularize imports and also optimize cjs require/exports to make sure you're not including og package into bundle if it's not being used. However, it's still not 100% can handle all the bundle optimization cases, such as `import {..} from "next/server.js"` could also ended up with the cjs bundle that failed the tree-shaking.

### Move on
So we decide to move og `ImageResponse` into a separate export `next/og`

Closes NEXT-1660
parent 3010ae10
......@@ -248,10 +248,10 @@ The `ImageResponse` constructor allows you to generate dynamic images using JSX
`ImageResponse` uses the [Edge Runtime](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#edge-runtime), and Next.js automatically adds the correct headers to cached images at the edge, helping improve performance and reducing recomputation.
To use it, you can import `ImageResponse` from `next/server`:
To use it, you can import `ImageResponse` from `next/og`:
```jsx filename="app/about/route.js"
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const runtime = 'edge'
......
......@@ -78,10 +78,10 @@ Generate an app icon by creating an `icon` or `apple-icon` route that default ex
| `icon` | `.js`, `.ts`, `.tsx` |
| `apple-icon` | `.js`, `.ts`, `.tsx` |
The easiest way to generate an icon is to use the [`ImageResponse`](/docs/app/api-reference/functions/image-response) API from `next/server`.
The easiest way to generate an icon is to use the [`ImageResponse`](/docs/app/api-reference/functions/image-response) API from `next/og`.
```tsx filename="app/icon.tsx" switcher
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
// Route segment config
export const runtime = 'edge'
......
......@@ -90,7 +90,7 @@ Generate a route segment's shared image by creating an `opengraph-image` or `twi
The easiest way to generate an image is to use the [ImageResponse](/docs/app/api-reference/functions/image-response) API from `next/server`.
```tsx filename="app/about/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
// Route segment config
export const runtime = 'edge'
......@@ -342,7 +342,7 @@ This example uses the `params` object and external data to generate the image.
> By default, this generated image will be [statically optimized](/docs/app/building-your-application/rendering/server-components#static-rendering-default). You can configure the individual `fetch` [`options`](/docs/app/api-reference/functions/fetch) or route segments [options](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to change this behavior.
```tsx filename="app/posts/[slug]/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const runtime = 'edge'
......@@ -382,7 +382,7 @@ export default async function Image({ params }: { params: { slug: string } }) {
```
```jsx filename="app/posts/[slug]/opengraph-image.js" switcher
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const runtime = 'edge'
......
......@@ -54,7 +54,7 @@ The `generateImageMetadata` function should return an `array` of objects contain
| `contentType` | `string` |
```tsx filename="icon.tsx" switcher
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export function generateImageMetadata() {
return [
......@@ -94,7 +94,7 @@ export default function Icon({ id }: { id: string }) {
```
```jsx filename="icon.js" switcher
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export function generateImageMetadata() {
return [
......@@ -140,7 +140,7 @@ export default function Icon({ id }) {
This example uses the `params` object and external data to generate multiple [Open Graph images](/docs/app/api-reference/file-conventions/metadata/opengraph-image) for a route segment.
```tsx filename="app/products/[id]/opengraph-image.tsx" switcher
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
import { getCaptionForImage, getOGImages } from '@/app/utils/images'
export async function generateImageMetadata({
......@@ -186,7 +186,7 @@ export default async function Image({
```
```jsx filename="app/products/[id]/opengraph-image.js" switcher
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
import { getCaptionForImage, getOGImages } from '@/app/utils/images'
export async function generateImageMetadata({ params }) {
......
......@@ -8,7 +8,7 @@ The `ImageResponse` constructor allows you to generate dynamic images using JSX
The following options are available for `ImageResponse`:
```jsx
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
new ImageResponse(
element: ReactElement,
......@@ -38,7 +38,8 @@ Please refer to [Satori’s documentation](https://github.com/vercel/satori#css)
## Version History
| Version | Changes |
| --------- | ---------------------------------------------------- |
| `v13.3.0` | `ImageResponse` can be imported from `next/server`. |
| `v13.0.0` | `ImageResponse` introduced via `@vercel/og` package. |
| Version | Changes |
| --------- | ----------------------------------------------------- |
| `v14.0.0` | `ImageResponse` moved from `next/server` to `next/og` |
| `v13.3.0` | `ImageResponse` can be imported from `next/server`. |
| `v13.0.0` | `ImageResponse` introduced via `@vercel/og` package. |
......@@ -399,6 +399,7 @@ pub async fn get_next_edge_import_map(
"next/router" => "next/dist/esm/client/router".to_string(),
"next/script" => "next/dist/esm/client/script".to_string(),
"next/server" => "next/dist/esm/server/web/exports/index".to_string(),
"next/og" => "next/dist/esm/server/og/image-response".to_string(),
"next/dist/client/components/headers" => "next/dist/esm/client/components/headers".to_string(),
"next/dist/client/components/navigation" => "next/dist/esm/client/components/navigation".to_string(),
......@@ -410,6 +411,7 @@ pub async fn get_next_edge_import_map(
"next/dist/shared/lib/dynamic" => "next/dist/esm/shared/lib/dynamic".to_string(),
"next/dist/shared/lib/head" => "next/dist/esm/shared/lib/head".to_string(),
"next/dist/shared/lib/image-external" => "next/dist/esm/shared/lib/image-external".to_string(),
"dist/server/og/image-response" => "next/dist/esm/server/og/image-response".to_string(),
},
);
......
export * from './dist/server/og/image-response'
module.exports = require('./dist/server/og/image-response')
......@@ -47,6 +47,8 @@
"jest.d.ts",
"amp.js",
"amp.d.ts",
"og.js",
"og.d.ts",
"index.d.ts",
"types/index.d.ts",
"types/global.d.ts",
......
......@@ -811,7 +811,7 @@ export default async function getBaseWebpackConfig(
],
alias: {
// Alias 3rd party @vercel/og package to vendored og image package to reduce bundle size
'@vercel/og': 'next/dist/server/web/spec-extension/image-response',
'@vercel/og': 'next/dist/server/og/image-response',
// Alias next/dist imports to next/dist/esm assets,
// let this alias hit before `next` alias.
......@@ -827,6 +827,8 @@ export default async function getBaseWebpackConfig(
// Alias the usage of next public APIs
[path.join(NEXT_PROJECT_ROOT, 'server')]:
'next/dist/esm/server/web/exports/index',
[path.join(NEXT_PROJECT_ROOT, 'og')]:
'next/dist/esm/server/og/image-response',
[path.join(NEXT_PROJECT_ROOT_DIST, 'client', 'link')]:
'next/dist/esm/client/link',
[path.join(
......@@ -1903,7 +1905,7 @@ export default async function getBaseWebpackConfig(
{
// Mark `image-response.js` as side-effects free to make sure we can
// tree-shake it if not used.
test: /[\\/]next[\\/]dist[\\/](esm[\\/])?server[\\/]web[\\/]exports[\\/]image-response\.js/,
test: /[\\/]next[\\/]dist[\\/](esm[\\/])?server[\\/]og[\\/]image-response\.js/,
sideEffects: false,
},
].filter(Boolean),
......
......@@ -587,7 +587,7 @@ function getExtractMetadata(params: {
const resource = module.resource
const hasOGImageGeneration =
resource &&
/[\\/]node_modules[\\/]@vercel[\\/]og[\\/]dist[\\/]index\.(edge|node)\.js$|[\\/]next[\\/]dist[\\/](esm[\\/])?server[\\/]web[\\/]spec-extension[\\/]image-response\.js$/.test(
/[\\/]node_modules[\\/]@vercel[\\/]og[\\/]dist[\\/]index\.(edge|node)\.js$|[\\/]next[\\/]dist[\\/](esm[\\/])?server[\\/]og[\\/]image-response\.js$/.test(
resource
)
......
{
"name": "@vercel/og",
"version": "0.5.15",
"LICENSE": "MLP-2.0",
"type": "module",
"main": "./index.node.js",
......@@ -9,6 +10,7 @@
"import": "./index.node.js",
"node": "./index.node.js",
"default": "./index.node.js"
}
},
"./package.json": "./package.json"
}
}
\ No newline at end of file
export class ImageResponse extends Response {
public static displayName = 'NextImageResponse'
constructor(
...args: ConstructorParameters<
typeof import('next/dist/compiled/@vercel/og').ImageResponse
>
) {
const readable = new ReadableStream({
async start(controller) {
const OGImageResponse: typeof import('next/dist/compiled/@vercel/og').ImageResponse =
// So far we have to manually determine which build to use,
// as the auto resolving is not working
(
await import(
process.env.NEXT_RUNTIME === 'edge'
? 'next/dist/compiled/@vercel/og/index.edge.js'
: 'next/dist/compiled/@vercel/og/index.node.js'
)
).ImageResponse
const imageResponse = new OGImageResponse(...args) as Response
if (!imageResponse.body) {
return controller.close()
}
const reader = imageResponse.body!.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
return controller.close()
}
controller.enqueue(value)
}
},
})
const options = args[1] || {}
super(readable, {
headers: {
'content-type': 'image/png',
'cache-control':
process.env.NODE_ENV === 'development'
? 'no-cache, no-store'
: 'public, immutable, no-transform, max-age=31536000',
...options.headers,
},
status: options.status,
statusText: options.statusText,
})
}
}
export class ImageResponse extends Response {
public static displayName = 'NextImageResponse'
constructor(
...args: ConstructorParameters<
typeof import('next/dist/compiled/@vercel/og').ImageResponse
>
) {
const readable = new ReadableStream({
async start(controller) {
const OGImageResponse: typeof import('next/dist/compiled/@vercel/og').ImageResponse =
// So far we have to manually determine which build to use,
// as the auto resolving is not working
(
await import(
process.env.NEXT_RUNTIME === 'edge'
? 'next/dist/compiled/@vercel/og/index.edge.js'
: 'next/dist/compiled/@vercel/og/index.node.js'
)
).ImageResponse
const imageResponse = new OGImageResponse(...args) as Response
if (!imageResponse.body) {
return controller.close()
}
const reader = imageResponse.body!.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) {
return controller.close()
}
controller.enqueue(value)
}
},
})
const options = args[1] || {}
super(readable, {
headers: {
'content-type': 'image/png',
'cache-control':
process.env.NODE_ENV === 'development'
? 'no-cache, no-store'
: 'public, immutable, no-transform, max-age=31536000',
...options.headers,
},
status: options.status,
statusText: options.statusText,
})
}
export function ImageResponse() {
throw new Error(
'ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead'
)
}
......@@ -228,6 +228,7 @@ export async function copy_vercel_og(task, opts) {
join(__dirname, 'src/compiled/@vercel/og/package.json'),
{
name: '@vercel/og',
version: require('@vercel/og/package.json').version,
LICENSE: 'MLP-2.0',
type: 'module',
main: './index.node.js',
......@@ -238,6 +239,7 @@ export async function copy_vercel_og(task, opts) {
node: './index.node.js',
default: './index.node.js',
},
'./package.json': './package.json',
},
},
{ spaces: 2 }
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
// without id
export async function generateImageMetadata({ params }) {
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export async function generateImageMetadata({ params }) {
return [
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const alt = 'Open Graph'
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export default function og() {
return new ImageResponse(
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const alt = 'Twitter'
export const size = { width: 1200, height: 675 }
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const contentType = 'image/png'
......
// This file should be ignored
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export default function favicon() {
return new ImageResponse(
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const contentType = 'image/png'
......
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const contentType = 'image/png'
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const contentType = 'image/png'
export const size = { width: 512, height: 512 }
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const alt = 'Open Graph'
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export const alt = 'Open Graph'
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
import { ImageResponse as ImageResponse2 } from '@vercel/og'
// Node.js: Using @vercel/og external package, and should be aliased to "next/server" ImageResponse
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
// @ts-ignore
import { ImageResponse as ImageResponse2 } from '@vercel/og'
......
......@@ -415,7 +415,7 @@ createNextDescribe(
it('should error when id is missing in generateImageMetadata', async () => {
const iconFilePath = 'app/metadata-base/unset/icon.tsx'
const contentMissingIdProperty = `
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export async function generateImageMetadata() {
return [
{
......
import { ImageResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export default function og() {
return new ImageResponse(
......
import { ImageResponse, NextResponse } from 'next/server'
import { NextResponse } from 'next/server'
import { ImageResponse } from 'next/og'
export async function middleware(req) {
console.log('middleware', req.url)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment