Serverless with Vercel
- use
vercel.json
to declare runtimes and routes you want in your application. Generally this will be one runtime, but vercel supportsruby
,golang
,python
andnodejs
{
"builds": [
{
"src": " **/*.html",
"use": "@now/static"
},
{
"src": "** /*.py",
"use": "@now/python"
},
{
"src": " **/*.js",
"use": "@now/node"
},
{
"src": "** /*.go",
"use": "@now/go"
}
],
"routes": [
{
"src": "/",
"dest": "public/index.html"
},
{
"src": "/py",
"dest": "api/hello.py"
},
{
"src": "/flask",
"dest": "api/flask.py"
},
{
"src": "/ping",
"dest": "api/ping.py"
},
{
"src": "/js",
"dest": "api/hello.js"
},
{
"src": "/go",
"dest": "api/app_go.go"
}
]
}
- create a directory called
api
. This ius where your route handlers will live. would be simple or complex logic injs
,go
,py
orrb
files. Example logics are give below
hello.py
from http.server import BaseHTTPRequestHandler class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/plain')
self.end_headers()
message = 'Hello from Python from a Serverless Function!'
self.wfile.write(message.encode())
return
hello.js
module.exports = (req, res) => {
res.json({
body: req.body,
query: req.query,
cookies: req.cookies
})
}
- in case you are using
modules
/packages
, you can declare the same inrequirements.txt
file (forpython
) andpackage.json
(fornodejs
) - For detailed instructions you can refer to links in referfences section below
development
environment
Running in - run
vercel dev
nodejs
function is in action athttp://localhost:3000/js
python
function is in action athttp://localhost:3000/py
Similarly, more runtimes will work. As mentioned if this seems tolo low-level, you can also have modules like bottle
, flask
to do server stuff in lesser lines in python
(install modules locally, setup venv
and doi pip install flask
for that, and modify code accordingly. an example is shown below)
flask.py
from flask import Flask, Response
app = Flask( __name__ )
def catch_all(path):
return Response("<h1>Flask</h1><p>You visited: /%s</p>" % (path), mimetype="text/html")
More on advanced usage here.
Also note, you can code in rust
, deno
, php
etc. with help of community built runtimes.
stage
or prod
environment
Running in - As with all things
vercel
, runvercel
orvercel --prod
to get the endpoints on the publicinternet
in yourvercel
account. You can then attach your domain also there.
References
- Awesome
vercel
documentation herezero · Automatic GitHub backup and more
Nice one.