Skip to content

Commit

Permalink
[edge api] allow wasm usage (#37836)
Browse files Browse the repository at this point in the history
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
Schniz and kodiakhq[bot] committed Jun 20, 2022
1 parent e28e513 commit 9184d6d
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 7 deletions.
11 changes: 11 additions & 0 deletions examples/with-webassembly/pages/api/edge.js
@@ -0,0 +1,11 @@
import add_module from '../../add.wasm?module'

const instance$ = WebAssembly.instantiate(add_module)

export default async function edgeExample() {
const { exports } = await instance$
const number = exports.add_one(10)
return new Response(`got: ${number}`)
}

export const config = { runtime: 'experimental-edge' }
15 changes: 8 additions & 7 deletions packages/next/build/webpack-config.ts
Expand Up @@ -1716,13 +1716,14 @@ export default async function getBaseWebpackConfig(

const webpack5Config = webpackConfig as webpack5.Configuration

webpack5Config.module?.rules?.unshift({
test: /\.wasm$/,
issuerLayer: 'middleware',
loader: 'next-middleware-wasm-loader',
type: 'javascript/auto',
resourceQuery: /module/i,
})
if (isEdgeServer) {
webpack5Config.module?.rules?.unshift({
test: /\.wasm$/,
loader: 'next-middleware-wasm-loader',
type: 'javascript/auto',
resourceQuery: /module/i,
})
}

webpack5Config.experiments = {
layers: true,
Expand Down
File renamed without changes.
Expand Up @@ -32,6 +32,44 @@ function baseNextConfig(): Parameters<typeof createNext>[0] {
}
}

describe('edge api endpoints can use wasm files', () => {
let next: NextInstance

beforeAll(async () => {
next = await createNext({
files: {
'pages/api/add.js': `
import { increment } from '../../src/add.js'
export default async (request) => {
const input = Number(request.nextUrl.searchParams.get('input')) || 1;
const value = await increment(input);
return new Response(null, { headers: { data: JSON.stringify({ input, value }) } });
}
export const config = { runtime: 'experimental-edge' };
`,
'src/add.wasm': new FileRef(path.join(__dirname, './add.wasm')),
'src/add.js': `
import wasm from './add.wasm?module'
const instance$ = WebAssembly.instantiate(wasm);
export async function increment(a) {
const { exports } = await instance$;
return exports.add_one(a);
}
`,
},
})
})
afterAll(() => next.destroy())
it('uses the wasm file', async () => {
const response = await fetchViaHTTP(next.url, '/api/add', { input: 10 })
expect(extractJSON(response)).toEqual({
input: 10,
value: 11,
})
})
})

describe('middleware can use wasm files', () => {
let next: NextInstance

Expand Down

0 comments on commit 9184d6d

Please sign in to comment.