Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NEXT-1047] OpenGraph does not work in AppDir dynamic routes #48704

Closed
1 task done
khuezy opened this issue Apr 22, 2023 · 13 comments · Fixed by #48844
Closed
1 task done

[NEXT-1047] OpenGraph does not work in AppDir dynamic routes #48704

khuezy opened this issue Apr 22, 2023 · 13 comments · Fixed by #48844
Assignees
Labels
area: app App directory (appDir: true) linear: next Confirmed issue that is tracked by the Next.js team.

Comments

@khuezy
Copy link
Contributor

khuezy commented Apr 22, 2023

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 22.3.0: Mon Jan 30 20:38:37 PST 2023; root:xnu-8792.81.3~2/RELEASE_ARM64_T6000
    Binaries:
      Node: 18.14.0
      npm: 9.3.1
      Yarn: 1.22.19
      pnpm: 7.27.0
    Relevant packages:
      next: 13.3.1
      eslint-config-next: N/A
      react: 18.2.0
      react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true)

Link to the code that reproduces this issue

https://github.com/khuezy/nextog

To Reproduce

  1. npm install
  2. npm run dev
  3. go to localhost:3000/api/og?title=hi
  4. Note that the OG works locally
  5. Deploy to vercel
  6. Go to the deployed site and append "/api/og?title=hi"
  7. See white page
  8. Go into Vercel dashboard and view logs
  9. Error: no such file or directory, open '/vercel/path0/node_modules/next/dist/compiled/@vercel/og/noto-sans-v27-latin-regular.ttf'

Describe the Bug

When using ImageResponse in a dynamic open graph endpoint, the request fails b/c of a missing font file that it tries to load.

NOTE: if you remove the "request" reference to grab the title (hence making the route static,) then it works w/o issue b/c it was able to load the font locally.

Expected Behavior

ImageResponse should work in dynamic app dir route.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

NEXT-1047

@khuezy khuezy added the bug Issue was opened via the bug report template. label Apr 22, 2023
@github-actions github-actions bot added the area: app App directory (appDir: true) label Apr 22, 2023
@huozhi huozhi self-assigned this Apr 22, 2023
@ReoHakase
Copy link

Having the same issue with runtime: "nodejs"😔 Would be so glad if it's fixed soon.

The code I have this problem with: astronomy-club-at-nitic/nitic-astronomy@06cf451
Error logs here:

Error: ENOENT: no such file or directory, open '/vercel/path0/node_modules/.pnpm/@vercel+og@0.5.3/node_modules/@vercel/og/dist/noto-sans-v27-latin-regular.ttf'
    at Object.openSync (node:fs:600:3)
    at Object.readFileSync (node:fs:468:35)
    at 2831 (/var/task/apps/website/.next/server/chunks/787.js:27909:48)
    at __webpack_require__ (/var/task/apps/website/.next/server/webpack-runtime.js:25:42)
    at 4442 (/var/task/apps/website/.next/server/app/api/ogimage/route.js:146:18)
    at __webpack_require__ (/var/task/apps/website/.next/server/webpack-runtime.js:25:42)
    at __webpack_exec__ (/var/task/apps/website/.next/server/app/api/ogimage/route.js:410:39)
    at /var/task/apps/website/.next/server/app/api/ogimage/route.js:411:77
    at __webpack_require__.X (/var/task/apps/website/.next/server/webpack-runtime.js:138:21)
    at /var/task/apps/website/.next/server/app/api/ogimage/route.js:411:47 {
  errno: -2,
  syscall: 'open',
  code: 'ENOENT',
  path: '/vercel/path0/node_modules/.pnpm/@vercel+og@0.5.3/node_modules/@vercel/og/dist/noto-sans-v27-latin-regular.ttf',
  page: '/api/ogimage'
}
RequestId: 678c3205-5352-40af-9050-b7b48ce82b17 Error: Runtime exited with error: exit status 1
Runtime.ExitError

Thanks in advance

@khuezy
Copy link
Contributor Author

khuezy commented Apr 22, 2023

@ReoHakase I notice you have a try {} block on the first line of your GET method. Can you add a console.log in your try block and run npm run build and let me know if you see the log? Related issue: #48701

From what I've seen, if you have code that doesn't reference your Request object immediately (this includes the try/catch), then next build treats it as static (prerenders)

@ReoHakase
Copy link

@ReoHakase I notice you have a try {} block on the first line of your GET method. Can you add a console.log in your try block and run npm run build and let me know if you see the log? Related issue: #48701

From what I've seen, if you have code that doesn't reference your Request object immediately (this includes the try/catch), then next build treats it as static (prerenders)

Hi dear @khuezy
In short, this api route app/api/ogimage/route.tsx is somehow recognized as static one as you assumed.
To be specific, I put a console.log in the first line of the try block and it got executed during next build
(I couldn't notice it since it works fine in next dev and my CI did not failed.)

The code

astronomy-club-at-nitic/nitic-astronomy@b74ff3f

export async function GET(request: Request) {
  try {
    console.log('\n@@@@@\nHey next build, can you see me? I am a console.log() in the first line of try block!\n@@@@@\n');
    // Parse parameters
    const { searchParams } = new URL(request.url);
    const props = OgPropsSchema.parse(Object.fromEntries(searchParams.entries()));

The next build output

pnpm website build

> nitic-astronomy@0.1.0 website /Users/ReoHakase/repos/nitic-astronomy
> pnpm --filter @nitic-astronomy/website "build"


> @nitic-astronomy/website@0.1.0 build /Users/ReoHakase/repos/nitic-astronomy/apps/website
> next build

warn  - You have enabled experimental features (appDir, typedRoutes) in next.config.js.
warn  - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use at your own risk.
info  - Thank you for testing `appDir` please leave your feedback at https://nextjs.link/app-feedback

(node:36919) [DEP_WEBPACK_MODULE_UPDATE_HASH] DeprecationWarning: Module.updateHash: Use new ChunkGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
info  - Creating an optimized production build
info  - Compiled successfully
info  - Linting and checking validity of types
info  - Collecting page data
[    ] info  - Generating static pages (0/8)
@@@@@
Hey next build, can you see me? I am a console.log() in the first line of try block!
@@@@@

Failed to generate an open graph image DynamicServerError: Dynamic server usage: request.url
    at Object.staticGenerationBailout (/Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/43.js:176:21)
    at handleReqBailout (/Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/753.js:2768:23)
    at Object.get (/Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/753.js:2776:13)
    at GET (/Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/app/api/ogimage/route.js:187:51)
    at /Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/753.js:3035:24
    at /Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/753.js:3950:36
    at NoopContextManager.with (/Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/753.js:591:30)
    at ContextAPI.with (/Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/753.js:261:58)
    at NoopTracer.startActiveSpan (/Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/753.js:1184:34)
    at ProxyTracer.startActiveSpan (/Users/ReoHakase/repos/nitic-astronomy/apps/website/.next/server/chunks/753.js:1224:36) {
  digest: 'DYNAMIC_SERVER_USAGE'
} NextRequest [Request] {
  [Symbol(realm)]: { settingsObject: { baseUrl: undefined } },
  [Symbol(state)]: {
    method: 'GET',
    localURLsOnly: false,
    unsafeRequest: false,
    body: null,
    client: { baseUrl: undefined },
    reservedClient: null,
    replacesClientId: '',
    window: 'client',
    keepalive: false,
    serviceWorkers: 'all',
    initiator: '',
    destination: '',
    priority: null,
    origin: 'client',
    policyContainer: 'client',
    referrer: 'client',
    referrerPolicy: '',
    mode: 'cors',
    useCORSPreflightFlag: false,
    credentials: 'same-origin',
    useCredentials: false,
    cache: 'default',
    redirect: 'follow',
    integrity: '',
    cryptoGraphicsNonceMetadata: '',
    parserMetadata: '',
    reloadNavigation: false,
    historyNavigation: false,
    userActivation: false,
    taintedOrigin: false,
    redirectCount: 0,
    responseTainting: 'basic',
    preventNoCacheCacheControlHeaderModification: false,
    done: false,
    timingAllowFailed: false,
    headersList: HeadersList {
      cookies: null,
      [Symbol(headers map)]: Map(0) {},
      [Symbol(headers map sorted)]: []
    },
    urlList: [ [URL] ],
    url: URL {
      href: 'http://localhost:3000/api/ogimage',
      origin: 'http://localhost:3000',
      protocol: 'http:',
      username: '',
      password: '',
      host: 'localhost:3000',
      hostname: 'localhost',
      port: '3000',
      pathname: '/api/ogimage',
      search: '',
      searchParams: URLSearchParams {},
      hash: ''
    }
  },
  [Symbol(signal)]: AbortSignal { aborted: false },
  [Symbol(headers)]: HeadersList {
    cookies: null,
    [Symbol(headers map)]: Map(0) {},
    [Symbol(headers map sorted)]: []
  },
  [Symbol(internal request)]: {
    cookies: RequestCookies { _parsed: Map(0) {}, _headers: [HeadersList] },
    geo: {},
    ip: undefined,
    nextUrl: NextURL { [Symbol(NextURLInternal)]: [Object] },
    url: 'http://localhost:3000/api/ogimage'
  }
}
info  - Generating static pages (8/8)
info  - Finalizing page optimization

Route (app)                                Size     First Load JS
┌ ○ /                                      155 B          74.3 kB
├ λ /api/ogimage                           0 B                0 B
├ ○ /article                               155 B          74.3 kB
├ λ /article/[articleId]                   156 B          74.3 kB
├ ○ /member                                155 B          74.3 kB
├ ○ /opengraph-image.png                   0 B                0 B
├ ○ /tag                                   156 B          74.3 kB
└ λ /tag/[tagId]                           156 B          74.3 kB
+ First Load JS shared by all              74.1 kB
  ├ chunks/44d352ec-aaa6716e893a996f.js    50.2 kB
  ├ chunks/883-a9e4ededbc8b4dbb.js         22 kB
  ├ chunks/main-app-7bddd938c64a3016.js    217 B
  └ chunks/webpack-00f84edd18d12def.js     1.69 kB

Route (pages)                              Size     First Load JS
─ ○ /404                                   179 B            86 kB
+ First Load JS shared by all              85.9 kB
  ├ chunks/main-b26e67a5a3887f3d.js        84 kB
  ├ chunks/pages/_app-ae4ca1da1b6cca3a.js  192 B
  └ chunks/webpack-00f84edd18d12def.js     1.69 kB

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)

@huozhi huozhi added linear: next Confirmed issue that is tracked by the Next.js team. and removed bug Issue was opened via the bug report template. labels Apr 24, 2023
@huozhi huozhi changed the title OpenGraph does not work in AppDir dynamic routes [NEXT-1047] OpenGraph does not work in AppDir dynamic routes Apr 24, 2023
@kodiakhq kodiakhq bot closed this as completed in #48844 Apr 26, 2023
kodiakhq bot pushed a commit that referenced this issue Apr 26, 2023
### Why

Default font file of `@vercel/og` is not loaded, because the og package is bundled by webpack and we should external it so that `fs.readFileSync` is bundled and manged that can't be traced by nft.


### How
This PR externals `@vercel/og` so that they don't need to be bundled and files can be properly traced

Closes NEXT-1047
Fixes #48704
ReoHakase added a commit to astronomy-club-at-nitic/nitic-astronomy that referenced this issue Apr 27, 2023
@huozhi
Copy link
Member

huozhi commented Apr 27, 2023

We land a fix in 13.3.2-canary.8, could you try again with that new canary version? 🙏

@blakebullis
Copy link

blakebullis commented Apr 27, 2023

Thank you for the attempt. I have tried canary.8 and canary.9 this morning and still seeing the error in my Vercel logs Error: ENOENT: no such file or directory, open '/vercel/path0/node_modules/@vercel/og/dist/noto-sans-v27-latin-regular.ttf.

I have tried both runtime = "edge" and runtime = "experimental-edge" and runtime = "nodejs". I also removed my try catch as well to see if that would change the result. No luck yet for me.

I'll keep an eye on the thread to see if someone else has better luck testing.

@khuezy
Copy link
Contributor Author

khuezy commented Apr 27, 2023

@huozhi I tried w/ latest canary.9 and got a different error:


errorMessage | Error: Cannot find module 'react/jsx-runtime'
Require stack:
- /var/task/node_modules/next/dist/server/require-hook.js
- /var/task/node_modules/next/dist/server/next-server.js

Downgraded to 13.3.1, trying canary .11 now. .11 also has issues.

@huozhi
Copy link
Member

huozhi commented Apr 27, 2023

@blakebullis would you mind sharing a reproduction for your case?

@khuezy
Copy link
Contributor Author

khuezy commented Apr 27, 2023

@huozhi Something in the 13.3.2-canary is breaking my standalone app. I'll try to pinpoint the canary version that breaks it.
All all 13.3.2-canary version breaks my standalone app...

The issue has been reported: #48918

@blakebullis
Copy link

blakebullis commented Apr 27, 2023

@huozhi

Here is some basic information about my app's request URL structure and directory structure. I also dumbed down my route.jsx file, it could help show I built the @vercel/og page.

It all works on localhost - but where Vercel is building and deploying my code - it cannot find the default font that is installed with the @vercel/og node module -- /vercel/path0/node_modules/@vercel/og/dist/noto-sans-v27-latin-regular.ttf

I don't know of any other way to share more details. The app is relatively new, so no custom-build scripts or network configurations besides what comes out of the box.

// e.g url request
// development: http://localhost:3000/en-us/images/test/hello.png
// production: https://www.petviibs.com/en-us/images/test/hello.png

// directory structure
// app/[lang]/images/test/[text]/route.jsx

Archive.zip

One thing that may be unique to me is I am running i18n-config and middleware.js for internationalization support(??)

@huozhi
Copy link
Member

huozhi commented Apr 27, 2023

@blakebullis could you file a new issue with a full reproduction?

@blakebullis
Copy link

@huozhi I think I got it working on next 13.3.2-canary.9

I changed the node module from @vercel/og to next/server. I did not realize there was an ImageResponse function in the latest next/server.

@khuezy I could not get the image working in an API endpoint like /api/image/route.jsx. I was only able to get it working inside the AppDir like /app/image/route.jsx.

Calling the URL directly worked fine in production.


Bug: Using next/image module <Image src="/image" /> would not load the relative image source URL for me. If I changed it to a standard HTML <img src="/image" /> image tag then the generated image would load.

@khuezy
Copy link
Contributor Author

khuezy commented May 4, 2023

This is now working in the latest 13.4.0, thanks! I had some unrelated issues that prevented me from confirming that it works. <3

@github-actions
Copy link
Contributor

github-actions bot commented Jun 4, 2023

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jun 4, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area: app App directory (appDir: true) linear: next Confirmed issue that is tracked by the Next.js team.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants