Combine multiple routes into one serverless function in Vercel using Python?

Question:

I currently have a Nextjs app with python api backend. The problem I am running into is that Vercel has a limit of 24 Serverless functions and they seem to recommend that one should combine your serverless functions to "optimize" your functions and avoid cold starts.

Currently I have the following code

from sanic import Sanic
from sanic.response import json
app = Sanic()


@app.route('/')
@app.route('/<path:path>')
async def index(request, path=""):
    return json({'hello': path})

@app.route('/other_route')
async def other_route(request, path=""):
    return json({'whatever': path})

However when I hit api/other_route I get a 404. I know that I can create separate file called other_route.py But I was wondering if there was a way to combine that route in my index.py route to avoid creating another serverless function.

Asked By: Kalimantan

||

Answers:

You need to create a vercel config in your project root vercel.json

{
    "routes": [{
        "src": "/api/(.*)",
        "dest": "api/index.py"
    }]
}

This routes all requests to / which is the Sanic instance. Sanic then knows how to route to the handler. You should also change your path arg in other_route method to be path="other_route"

Answered By: SeanAye
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.