server (api) example?
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 */
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
Thanks a lot! Here is some of my findings to save you some time.
- still opened issue with server-side wasm loading - I tested both web and nodejs targets. It looks like nodejs target is more promising, but as discussed in that issue and comments - it's a pain to make webpack handle paths properly.
- my attempts to use rust runtime and WasmEdge runtime
- best thing I ever saw - working server-side example - but it's without js bindings, which I'd prefer to have.
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.
Thank you @YuriGor. Sure, feel free to contribute 🛰️
Another example / more findings here: https://github.com/vercel/next.js/issues/29362#issuecomment-1278868452