nextjs-wasm icon indicating copy to clipboard operation
nextjs-wasm copied to clipboard

server (api) example?

Open YuriGor opened this issue 3 years ago • 5 comments

Hello, thanks for template. Could you share some example how to import/use wasm in api? I tried to add /pages/api/test.js: async loading as you do in context is failing due to fetch issue:

export default async (req, res) => {
  const wasm = await import('wasm')
  await wasm.default();
  res.json('test',wasm.add(3,4));
  res.end();
};
/* TypeError: Only absolute URLs are supported
    at getNodeRequestOptions (/home/gor/Development/test-wasm/node_modules/next/dist/compiled/node-fetch/index.js:1:63538)
*/

direct import also doesn't work:

import {add} from 'wasm';
export default async (req, res) => {
  res.json('test',add(34));
  res.end();
};
/* wasm is not loaded in pkg/wasm.js */

YuriGor avatar Jul 25 '22 17:07 YuriGor

Hi @YuriGor! Thanks for visiting this repo and creating the issue.

That's a good point which I wasn't aware when I was creating this repository. My main purpose was to bring it to client side (browser).

If I'll have time in the coming weeks, I'll dig in and prepare some example for server side.

I think the main reason why it doesn't work at this point is because wasm-bingen's target is set to web, ref: https://github.com/satelllte/nextjs-wasm/blob/9f1d2a00af1e3ed33a5dfdc1714f41e5185c9831/package.json#L6

There are other options available including nodejs, here's the doc: https://rustwasm.github.io/wasm-bindgen/reference/deployment.html

In case you urgently need it on server, that's a good starting point

satelllte avatar Jul 25 '22 17:07 satelllte

Thanks a lot! Here is some of my findings to save you some time.

YuriGor avatar Jul 25 '22 18:07 YuriGor

Ok, finally, by using this example I was able to run api with assembly compiled by wasm-pack with target web.

Main trick was to feed js wrapper produced by wasm-pack with wasm module manually imported in edge api instead of letting him fail to fetch wasm automatically.

It's still not perfect, because works only with edge runtime which has significant limitations.

I'll maybe fork and enhance that example with second wasm prepared by wasm-pack, so people will have more options, because currently wasm+nextjs is still shadow zone.

If you will find a way to do the same with nodejs runtime on backend - would be great. With edge runtime a lot of questions arise about session, db, auth etc.

YuriGor avatar Jul 25 '22 20:07 YuriGor

Thank you @YuriGor. Sure, feel free to contribute 🛰️

satelllte avatar Jul 25 '22 20:07 satelllte

Another example / more findings here: https://github.com/vercel/next.js/issues/29362#issuecomment-1278868452

kachkaev avatar Oct 14 '22 15:10 kachkaev