Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Serverless Function Vercel - Next.js

I found out that I could use Python to create a serverless function inside a Next.js project. Once deployed to Vercel, it will get converted into a serverless function.

I went through the docs and found a simple example that outputs the date:

from http.server import BaseHTTPRequestHandler
from datetime import datetime

class handler(BaseHTTPRequestHandler):

  def do_GET(self):
    self.send_response(200)
    self.send_header('Content-type', 'text/plain')
    self.end_headers()
    self.wfile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode())
    return

They offer a live working example here.

Apparently all that is needed is to place the file date.py inside the api folder of a bootstrapped Next.js project and you're off to the races. When deployed, Vercel will detect the Python file and serve it as a serverless function.

The deploy succeeded and I placed the file inside the pages/api folder as required. However, the function is never picked up (image below): vercel function output

Older versions apparently required the configuration of serverless functions by adding a vercel.json file. But this doesn't seem necessary now.

What am I missing?

like image 412
Juan Marco Avatar asked Aug 29 '20 21:08

Juan Marco


1 Answers

After going over the FAQs. I found an entry named Unmatched Function Pattern, it states:

the functions property uses a glob pattern for each key. This pattern must match Serverless Function source files within the api directory.

It also mentions:

if you'd like to use a Serverless Function that isn't written with Node.js in combination with Next.js, you can place it in the api directory (provided by the platform), since pages/api (provided by Next.js) only supports JavaScript.

I think that this needs to be clarified a bit. There is indeed an default api folder when you bootstrap a Next.js project with create-next-app, but it's created inside the pages directory.

If you follow the example they give, you might just go ahead and create a serverless function in a supported language (other than JavaScript) inside the pages/api directory and wonder why Vercel doesn't pick it up when you deploy.

In short, if you're using another language to write a serverless function inside a Next.js project. Be sure to place it inside an api folder that sits in the root directory of the project (if there's none, create one).

Thanks to @evgenifotia for the suggestion, it pointed me in the right direction and helped me solve this issue.

Note: You can only have a single api directory that houses serverless functions. Either you have a pages/api directory or a api directory in the root folder, having both in a single project is not supported.

like image 135
Juan Marco Avatar answered Sep 29 '22 19:09

Juan Marco