Skip to content

SubtleCrypto importKey broken in Edge Runtime on Nodejs 18.17+ #54588

Closed
@acburdine

Description

@acburdine

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.6.0: Wed Jul  5 22:21:53 PDT 2023; root:xnu-8796.141.3~6/RELEASE_ARM64_T6020
    Binaries:
      Node: 18.17.1
      npm: 9.8.1
      Yarn: 1.22.19
      pnpm: N/A
    Relevant Packages:
      next: 13.4.20-canary.9
      eslint-config-next: 13.4.19
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.2.2
    Next.js Config:
      output: N/A

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

Middleware / Edge (API routes, runtime)

Link to the code that reproduces this issue or a replay of the bug

https://github.com/acburdine/nextjs-edge-runtime-error

To Reproduce

Step 1. Install Node.js > 18.17 (or latest v20)
Step 2. Run npm run dev to start the repro
Step 3. Visit http://localhost:3000/test/sign.json to invoke the middleware, see a 500 error due to importKey failing
Step 4. Visit http://localhost:3000/api/test to view { success: true }

Describe the Bug

On Nodejs v18.17 and above (and on latest Node v20), SubtleCrypto.importKey fails due to a TypeError in the Next.js Edge Runtime.

The specific error message is:

TypeError: Failed to execute 'importKey' on 'SubtleCrypto': 2nd argument is not instance of ArrayBuffer, Buffer, TypedArray, or DataView.

This does not occur in the API routes runtime - the reproduction case above demonstrates that, invoking the same shared code, API routes work while middleware does not.

I haven't checked other SubtleCrypto functions, so there could be other type errors that occur there as well.

Given that this issue does not occur in Node v18.16 or earlier, I did some digging in the nodejs changelog and discovered this PR which was included in v18.17: nodejs/node#46067. As far as I can tell, the validation logic was tightened up in some of the WebCrypto nodejs apis, and that would explain the bug here. I'm not familiar enough with how the edge runtime works within Node, but perhaps the bundling for the edge runtime is doing something that doesn't play well with the increased validation rules.

Expected Behavior

The error should not occur with valid use of the SubtleCrypto importKey function in the Edge Runtime

Which browser are you using? (if relevant)

Chrome

How are you deploying your application? (if relevant)

Docker

Metadata

Metadata

Assignees

No one assigned

    Labels

    RuntimeRelated to Node.js or Edge Runtime with Next.js.bugIssue was opened via the bug report template.locked

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions