I am hosting a REST API in Vercel (serverless). The root directry looks like this:
+ myapp_root_dir
|-+ api
| |-+ public
| | |-- index.html
| | |-- layout.css
| | |-- main.js
| |-- index.js
|-- vercel.json
This is the server code (index.js):
import express form 'express'
import session from 'express-session';
import cors from 'cors'
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express()
app.use(session({
secret: 'somesecrethere',
resave: true,
saveUninitialized: true,
cookie: {
secure: false,
}
}))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded())
app.use(express.static("public", {
index: false
}))
app.get("/", (req, res) => {
res.sendFile(__dirname + "/public/index.html")
})
app.get("/time", (req, res) => {
res.send(new Date().getTime())
})
export default app
And this is the vercel.json config file
{
"rewrites": [
{ "source": "/time", "destination": "/api" },
{ "source": "/", "destination": "/api" }
]
}
The /time endpoint is working correctly and returns the current time. However, the / endpoint returns the server code (the contents of index.js).
Edit: I was able to get around this issue by moving the / handler to a new route (home) and placing a redirect in vercel.json:
{
"rewrites": [...],
"redirects": [
{ "source": "/", "destination": "/home" }
]
}
What is so weird is that I have another app with the same vercel.json config that is working perfectly well. So what is going wrong here?