My React/NextJS front end has a Button component that fetches data via a serverless function when the button is clicked. I want to test this functionality during local development with the Vercel dev/CLI tools, as manetioned here https://adevait.com/javascript-developers/build-a-headless-trello-clone I am getting a 404 result when attempting to access my lambda functions. Here are the approximate steps that I’ve gone through so far:
Result:
I'm receiving a 404 response
Note: I can access the lambda function from localhost:3000/pages/api/validate.py (vercel dev server address). This appears to manually kickstart the lambda function build and serve process. I thought that it should have been built and served already from the vercel.json specification and be available at localhost:3001/api/validate. This seems to agree with the Vercel documentation.
Note 2: Next dev/CLI tools build and serve javascript/typescript files just fine. I'm using python and Go functions as well, which are supported by Vercel dev/CLI but not Next
- Create package.json with a dev script:
Code:
...
"scripts": {
"dev": "yarn codegen && next --hostname=0.0.0.0 --port=3001",
}
...
- Link to deployed vercel project
- Create vercel.json to specify builds and routes:
Code:
...
"builds": [
{ "src": "*.html", "use": "@now/static" },
{ "src": "pages/api/*.py", "use": "@now/python" },
],
"routes": [
{ "src": "/api/validate", "dest": "/pages/api/validate.py" }
]
...
- Create my test Lambda function (in python):
Code:
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
- Create my Button component:
Code:
...
<Button
variant="contained"
color="secondary"
onClick={() => {
fetch('api/validate')
.then(response => { console.log(response)
response.json() })
.then(data => console.log(data))
}}
>
Generate sample dataset
</Button>
...
- Run vercel dev
- Access website at localhost:3001 (next dev server address)
- Click button
Result:
I'm receiving a 404 response
Note: I can access the lambda function from localhost:3000/pages/api/validate.py (vercel dev server address). This appears to manually kickstart the lambda function build and serve process. I thought that it should have been built and served already from the vercel.json specification and be available at localhost:3001/api/validate. This seems to agree with the Vercel documentation.
Note 2: Next dev/CLI tools build and serve javascript/typescript files just fine. I'm using python and Go functions as well, which are supported by Vercel dev/CLI but not Next