Running a Python ASGI app on Vercel

Vercel really wants you to deploy static assets with serverless functions tucked away in a separate folder. They suggest creating modules like api/index.py which will be served up automatically as API backends to your client-side JavaScript.

It turns out you can subvert that model entirely and route all of your traffic through a single function - great for serving up Python WSGI or ASGI apps that handle traffic routing themselves.

the trick is to use the "routes" key in a vercel.json file like this:

{
    "version": 2,
    "builds": [
        {
            "src": "json_head.py",
            "use": "@vercel/python"
        }
    ],
    "routes": [
        {
            "src": "(.*)",
            "dest": "json_head.py"
        }
    ]
}

Here json_head.py is a Python module which uses Sanic to expose a app object that conforms to the ASGI protocol. The same trick works for Starlette too, and should work for libraries that expose WSGI protocol objects such as Flask.

Some examples I've built that use this pattern:

Here's the Vercel builder code that detects ASGI or WSGI apps, for a peek at how it works under the hood.

See also:

Created 2020-04-19T15:28:51-07:00, updated 2023-03-26T09:18:18-07:00 · History · Edit