A template project for building high-performance, portable, and safe serverless functions in Vercel.

Overview

Tutorial | Demo for image processing | Demo for tensorflow

This is a Next.js project bootstrapped with create-next-app.

This project is aimed to demonstrate how to implement a Serverless Functions working with Webassembly in Vercel. The main branch showcases an image processing function, and the tensorflow branch showcases an AI inference function. Both written in simple Rust and runs in the WasmEdge runtime for WebAssembly.

Overview

The Serverless Functions endpoint is located at api/hello.js to meet the requirement of Vercel, but not to the Next.js. So if you want to develop on you local machine, you should put it into pages/api/ and make some change.

The only function in api/hello.js is grayscaling an image. It receives a png file and pass it as stdin stream to a spawned child process. The child process runs using the WasmEdge command.

File api/functions/image-grayscale/src/main.rs implements the grayscaling logic. You can build it with the Rust cargo command with the -target wasm32-wasi option to get the grayscale.wasm file.

We define Custom Build in api/pre.sh to download the WasmEdge command.

Learn More

A code walk-through for this template project is available in this tutorial on the TNS.

To learn more about Next.js, take a look at the following resources:

You can check out the Next.js GitHub repository - your feedback and contributions are welcome!

To learn more about Serverless Functions in Vercel, take a look at the following resources:

Deploy on Vercel

The easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js.

Check out our Next.js deployment documentation for more details.

You might also like...

Create GraphQL schema and resolvers with TypeScript, using classes and decorators!

Create GraphQL schema and resolvers with TypeScript, using classes and decorators!

TypeGraphQL Create GraphQL schema and resolvers with TypeScript, using classes and decorators! https://typegraphql.com/ Introduction TypeGraphQL makes

Jan 9, 2023

🥚 Born to build better enterprise frameworks and apps with Node.js & Koa

🥚 Born to build better enterprise frameworks and apps with Node.js & Koa

Features Built-in Process Management Plugin System Framework Customization Lots of plugins Quickstart Follow the commands listed below. $ mkdir showca

Dec 29, 2022

Fast and low overhead web framework, for Node.js

Fast and low overhead web framework, for Node.js

An efficient server implies a lower cost of the infrastructure, a better responsiveness under load and happy users. How can you efficiently handle the

Jan 2, 2023

🚀 The Node.js Framework highly focused on developer ergonomics, stability and confidence

🚀 The Node.js Framework highly focused on developer ergonomics, stability and confidence

Sponsored by FOSS United is a non-profit foundation that aims at promoting and strengthening the Free and Open Source Software (FOSS) ecosystem in Ind

Dec 31, 2022

MVC framework making it easy to write realtime, collaborative applications that run in both Node.js and browsers

Derby The Derby MVC framework makes it easy to write realtime, collaborative applications that run in both Node.js and browsers. Derby includes a powe

Dec 23, 2022

Actionhero is a realtime multi-transport nodejs API Server with integrated cluster capabilities and delayed tasks

Actionhero is a realtime multi-transport nodejs API Server with integrated cluster capabilities and delayed tasks

Actionhero The reusable, scalable, and quick node.js API server for stateless and stateful applications NPM | Web Site | Latest Docs | GitHub | Slack

Jan 4, 2023

:seedling: Next-Gen AI-Assisted Isomorphic Application Engine for Embedded, Console, Mobile, Server and Desktop

lychee.js Mono Repository Important Notes to follow through Installation Quirks: The lycheejs-engine Repository needs to be installed to the path /opt

Dec 31, 2022

Easily add filtering, sorting, and pagination to your Node.js REST API through your old friend: the query string!

QueryQL QueryQL makes it easy to add filtering, sorting, and pagination to your Node.js REST API through your old friend: the query string! Read our i

Dec 27, 2022

AWS Lambda & Serverless - Developer Guide with Hands-on Labs. Develop thousands line of aws lambda functions interact to aws serverless services with real-world hands-on labs

AWS Lambda & Serverless - Developer Guide with Hands-on Labs. Develop thousands line of aws lambda functions interact to aws serverless services with real-world hands-on labs

AWS Lambda & Serverless - Developer Guide with Hands-on Labs UDEMY COURSE WITH DISCOUNTED - Step by Step Development of this Repository - https://www

Dec 17, 2022

Functions and objects that make it easier to add fields to Portable Text editors for accessibility meta information, like language changes or abbreviations.

Porta11y Porta11y is a collection of accessibility-focused annotations, decorators and validators for Sanity’s Portable Text editor. Portable Text is

Aug 25, 2022

A developer directory built on Next.js and MongoDB Atlas, deployed on Vercel with the Vercel + MongoDB integration.

A developer directory built on Next.js and MongoDB Atlas, deployed on Vercel with the Vercel + MongoDB integration.

MongoDB Starter – Developer Directory A developer directory built on Next.js and MongoDB Atlas, deployed on Vercel with the Vercel + MongoDB integrati

Dec 20, 2022

Highly opinionated project template for Serverless Framework that follows and applies hexagonal architecture principle to serverless world. Prepared with easy testing in mind.

Highly opinionated project template for Serverless Framework that follows and applies hexagonal architecture principle to serverless world. Prepared with easy testing in mind.

serverless-hexagonal-template Highly opinionated project template for Serverless Framework that applies hexagonal architecture principles to the serve

Dec 26, 2022

Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

May 18, 2022

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 3, 2022

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

A URL shortener website and PWA build with vercel serverless cloud function, MongoDB and nodeJS

A URL shortener website and PWA build with vercel serverless cloud function, MongoDB and nodeJS

❤️ lenk.cf A URL shortner made using NodeJS, MongoDB and Vercel serverless function. This project also includes a serverless API. With the help of thi

Nov 5, 2022

Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Jan 2, 2023

An open-source link shortener built with Vercel Edge Functions and Upstash Redis.

Dub An open-source link shortener built with Vercel Edge Functions and Upstash Redis. Introduction · Deploy Your Own · Contributing Introduction Dub i

Jan 5, 2023

A Serverless GraphQL Sample project using Apollo and Serverless Framework with TypeScript and Webpack.

Serverless GraphQL Boilerplate This is a base project with a structure that includes Serverless Framework, Apollo, TypeScript and Webpack. It can be d

Aug 23, 2022
Comments
  • Can't Get Local Dev Environment Working - Error: spawn /wasmedge ENOENT

    Can't Get Local Dev Environment Working - Error: spawn /wasmedge ENOENT

    What's happening

    I can't seem to get this working in a local WSL dev environment. It deploys to Vercel / Netlify and processes the image as expected. On the loca side, the server crashes as soon as you click "run wasm"

    These are the steps I've taken:

    1. wasmedge runtime installed per WASM Edge Book

    2. Ran the ./pre.sh file with success / no errors

    3. yarn dev Brings up the front end no problem

    Troubleshooting

    • updated WSL
    • updated / upgraded distro (Ubuntu 20.04.3 LTS)
    • completely removed and reinstall wasmedge
    • deleted and cloned repo

    This is when it happens:

    Uploading image works just fine. Once you click "Run WASM" nextjs / node crashes with the error below. On the FE it just shows the little broken image. Screenshot_1

    Environment:

    • Node v16.3.0
    • Ubuntu 20.04.3 LTS
    • Chrome 97.0.4692.99 (Windows x64)
    event - compiled successfully
    API resolved without sending a response for /api/hello, this may result in stalled requests.
    Error: spawn /wasmedge ENOENT
    
        at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
        at onErrorNT (node:internal/child_process:480:16)
        at processTicksAndRejections (node:internal/process/task_queues:83:21) {
      errno: -2,
      code: 'ENOENT',
      syscall: 'spawn /wasmedge',
      path: '/wasmedge',
      spawnargs: [ '/grayscale.wasm' ]
    }
    node:_http_outgoing:574
        throw new ERR_HTTP_HEADERS_SENT('set');
        ^
    
    Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
        at new NodeError (node:internal/errors:363:5)
        at ServerResponse.setHeader (node:_http_outgoing:574:11)
        at ChildProcess.<anonymous> (/home/chris/Coding/vercel-wasm-runtime/.next/server/pages/api/hello.js:119:9)
        at ChildProcess.emit (node:events:394:28)
        at maybeClose (node:internal/child_process:1067:16)
        at Socket.<anonymous> (node:internal/child_process:453:11)
        at Socket.emit (node:events:394:28)
        at Pipe.<anonymous> (node:net:661:12) {
      code: 'ERR_HTTP_HEADERS_SENT'
    }
    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.```
    opened by Pandaphobic 2
  • Demo failing on Vercel - Runtime.UnhandledPromiseRejection

    Demo failing on Vercel - Runtime.UnhandledPromiseRejection

    Would love to get this working - hitting this error on Vercel:

    [GET] /api/hello
    20:36:29:56
    2021-09-11T13:36:30.095Z	be9096ad-e534-4368-943b-9c6fee2dd916	ERROR	Unhandled Promise Rejection 	{"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError [ERR_INVALID_ARG_TYPE]: The \"chunk\" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined","reason":{"errorType":"TypeError","errorMessage":"The \"chunk\" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined","code":"ERR_INVALID_ARG_TYPE","stack":["TypeError [ERR_INVALID_ARG_TYPE]: The \"chunk\" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined","    at Socket.Writable.write (internal/streams/writable.js:285:13)","    at module.exports (/var/task/api/hello.js:20:18)","    at Server.<anonymous> (/var/task/___vc/__helpers.js:813:19)","    at Server.emit (events.js:400:28)","    at parserOnIncoming (_http_server.js:897:12)","    at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: TypeError [ERR_INVALID_ARG_TYPE]: The \"chunk\" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined","    at process.<anonymous> (/var/runtime/index.js:35:15)","    at process.emit (events.js:412:35)","    at processPromiseRejections (internal/process/promises.js:245:33)","    at processTicksAndRejections (internal/process/task_queues.js:96:32)"]}
    Unknown application error occurred
    
    

    opened by mirkokiefer 2
  • Nextjs /pages/api doesn't work

    Nextjs /pages/api doesn't work

    Hi, I am trying to adopt this example in my nextjs project and once I am adding /api to the root of project - it works, but /pages/api stops working. Moving all the /pages/api to /api is not an option - it doesn't work properly (nextjs api work differently then vercel api) Should we instead move rust api to /pages/api? Could you provide working example?

    I expect this potential issues:

    • package.json / vercel-build may be ignored under /pages so we will need to use package.json from the root of project
    • wasm/.so files will not be deployed by default, this in theory is possible through nextjs config / webpack options.
    opened by YuriGor 1
Owner
Second State
Fast, safe, portable & serverless. Deploy Rust functions in edge computing, Jamstack, SaaS and service mesh applications.
Second State
🍔 A Node.js Serverless Framework for front-end/full-stack developers. Build the application for next decade. Works on AWS, Alibaba Cloud, Tencent Cloud and traditional VM/Container. Super easy integrate with React and Vue. 🌈

Midway - 一个面向未来的云端一体 Node.js 框架 English | 简体中文 ?? 欢迎观看 Midway Serverless 2.0 发布会回放: https://www.bilibili.com/video/BV17A411T7Md 《Midway Serverless 发布

Midway.js 6.3k Jan 8, 2023
A serverless web framework for Node.js on AWS (CloudFormation, CloudFront, API Gateway, Lambda)

---- Sorry, this project is not maintained anymore. ---- dawson is a serverless web framework for Node.js on AWS (CloudFormation, CloudFront, API Gate

dawson 717 Dec 30, 2022
Expressive middleware for node.js using ES2017 async functions

Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-li

Koa.js 33.5k Jan 4, 2023
A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications on top of TypeScript & JavaScript (ES6, ES7, ES8) 🚀

A progressive Node.js framework for building efficient and scalable server-side applications. Description Nest is a framework for building efficient,

nestjs 53.2k Dec 31, 2022
Marble.js - functional reactive Node.js framework for building server-side applications, based on TypeScript and RxJS.

Functional reactive Node.js framework for building server-side applications, based on TypeScript and RxJS. Ecosystem Name Description @marblejs/core F

Marble.js 2.1k Dec 16, 2022
Catberry is an isomorphic framework for building universal front-end apps using components, Flux architecture and progressive rendering.

Catberry What the cat is that? Catberry was developed to help create "isomorphic/Universal" Web applications. Long story short, isomorphic/universal a

Catberry.js 801 Dec 20, 2022
A well documented set of tools for building node web applications.

Perk Framework Perk is a well documented set of tools for building node web applications. The goal of Perk is first and foremost to provide a well doc

Aaron Larner 179 Oct 26, 2022
Zeronode - minimal building block for NodeJS microservices

Zeronode - minimal building block for NodeJS microservices Why Zeronode? Installation Basics Benchmark API Examples Basic Examples Basic Examples [Adv

Steadfast 120 Oct 21, 2022
Application structure for new adonis app, think of it as scaffolding a new project

AdonisJs Application This repo is the pre-configured project structure to be used for creating ambitious web servers using AdonisJs. Make sure to star

AdonisJS Framework 375 Oct 15, 2022
A framework for real-time applications and REST APIs with JavaScript and TypeScript

A framework for real-time applications and REST APIs with JavaScript and TypeScript Feathers is a lightweight web-framework for creating real-time app

Feathers 14.3k Jan 1, 2023