Serverless Function to backend
Answered
Felipe posted this in #help-forum

FelipeOP
Hi everyone! I'm doing a project for school in which I'm using NextJS to create an app. I have some api calls on a backend, and I saw this Vercel tutorial https://www.youtube.com/watch?v=yLMODEUPJdU on how to setup a Serverless Function. But I'm a bit lost on how to actually run it. Can anyone help me? Thanks!
This is my current file structure for the backend. I ran
This is my current file structure for the backend. I ran
vercel
on the terminal and created a project on Vercel linked to it.
55 Replies

FelipeOP
I already have the project deployed, but when I go on to test the api using ThunderClient, it returns this


FelipeOP


@Felipe Hi everyone! I'm doing a project for school in which I'm using NextJS to create an app. I have some api calls on a backend, and I saw this Vercel tutorial https://www.youtube.com/watch?v=yLMODEUPJdU on how to setup a Serverless Function. But I'm a bit lost on how to actually run it. Can anyone help me? Thanks!
This is my current file structure for the backend. I ran `vercel` on the terminal and created a project on Vercel linked to it.

For me, I needed to add all my files inside
api
folder, with this addition in next config: "rewrites": [
{
"source": "/(.*)",
"destination": "/api"
}
],
and export app in
api/index.ts

@Felipe Hi everyone! I'm doing a project for school in which I'm using NextJS to create an app. I have some api calls on a backend, and I saw this Vercel tutorial https://www.youtube.com/watch?v=yLMODEUPJdU on how to setup a Serverless Function. But I'm a bit lost on how to actually run it. Can anyone help me? Thanks!
This is my current file structure for the backend. I ran `vercel` on the terminal and created a project on Vercel linked to it.

Black carpenter ant
can you share your vercel.json

FelipeOP
sure!
{
"version": 2,
"builds": [
{
"src": "server.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/api/(.*)",
"dest": "server.js"
}
]
}

@Felipe
{
"version": 2,
"builds": [
{
"src": "server.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/api/(.*)",
"dest": "server.js"
}
]
}

Black carpenter ant
could you share the server.js too?

FelipeOP
Okay, I renamed the folder to api

Black carpenter ant
i was thinking, you're using basic project, but you're using server.js

@Felipe Okay, I renamed the folder to api

Black carpenter ant
no it isn't needed, change it back to the routes
share any one of the routes too

@Felipe
{
"version": 2,
"builds": [
{
"src": "server.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/api/(.*)",
"dest": "server.js"
}
]
}

if you're using
@vercel/node
, then renaming to api is not needed.It didn't really work well for me last I tried, but you can try if it works for you

@Black carpenter ant *i was thinking, you're using basic project, but you're using server.js*

FelipeOP
I don't know If I'm doing it right, my professor said we could host it on vercel. Maybe I can't?

@Felipe I don't know If I'm doing it right, my professor said we could host it on vercel. Maybe I can't?

Black carpenter ant
what it does?

you can host on vercel

Black carpenter ant
if it's only using simple things, http methods and all, you can host it on vercel!
if you aren't familiar with vercel functions, you can use express.js
https://vercel.com/guides/using-express-with-vercel
https://vercel.com/guides/using-express-with-vercel

@Black carpenter ant what it does?

FelipeOP
it uses gemini to send product recommendations to a page, based on the user preferences

@Felipe it uses gemini to send product recommendations to a page, based on the user preferences

Black carpenter ant
alright, it looks like you haven't shared the server.js yet

@Black carpenter ant if you aren't familiar with vercel functions, you can use express.js
https://vercel.com/guides/using-express-with-vercel

Thats what I was guiding him with, when I told to rename to
api

FelipeOP
Here it is!
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const recommendationsRouter = require('./routes/recommendations');
const scrapeRoute = require('./routes/scrape');
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors({
origin: ['http://localhost:3000', 'https://beauty-finder.vercel.app']
}));
app.use(express.json());
// Routes
app.use('/api/recommendations', recommendationsRouter);
app.use('/api', scrapeRoute);
// Error handling
app.use((err, req, res, next) => {
console.error('Server Error:', err);
res.status(500).json({
error: 'Internal server error',
message: process.env.NODE_ENV === 'production' ? 'Something went wrong' : err.message
});
});
module.exports = app;
// Start server if not in production
if (process.env.NODE_ENV !== 'production') {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`- Recommendations API: http://localhost:${PORT}/api/recommendations`);
console.log(`- Scraping API: http://localhost:${PORT}/api/scrape`);
});
}

This is a express app only
You are doing everything right, just:
- create a folder
- put your js files in it, like
- rename
It should work then
- create a folder
api
- put your js files in it, like
server.js
and routes- rename
server.js
, where you've app
setup, to index.js
It should work then

@Felipe javascript
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const recommendationsRouter = require('./routes/recommendations');
const scrapeRoute = require('./routes/scrape');
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors({
origin: ['http://localhost:3000', 'https://beauty-finder.vercel.app']
}));
app.use(express.json());
// Routes
app.use('/api/recommendations', recommendationsRouter);
app.use('/api', scrapeRoute);
// Error handling
app.use((err, req, res, next) => {
console.error('Server Error:', err);
res.status(500).json({
error: 'Internal server error',
message: process.env.NODE_ENV === 'production' ? 'Something went wrong' : err.message
});
});
module.exports = app;
// Start server if not in production
if (process.env.NODE_ENV !== 'production') {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`- Recommendations API: http://localhost:${PORT}/api/recommendations`);
console.log(`- Scraping API: http://localhost:${PORT}/api/scrape`);
});
}

Black carpenter ant
This should surely help
https://vercel.com/guides/using-express-with-vercel#5.-configure-your-project-for-vercel
https://vercel.com/guides/using-express-with-vercel#5.-configure-your-project-for-vercel

FelipeOP
Okay, I'll try it!
Thanks guys! I'll send another message if I have other issues!! Thanks a lot!

@Anay-208 | Ping on replies You are doing everything right, just:
- create a folder `api`
- put your js files in it, like `server.js` and routes
- rename `server.js`, where you've `app` setup, to `index.js`
It should work then

FelipeOP
I did this, but I'm still getting Not found. This is my vercell projects tab. What may be the issue now?


This is the repo, with the api folder and renaming, as suggested @Anay-208 | Ping on replies


Can you share your index.js and vercel.json once again?
@Felipe

FelipeOP
Yes!
index.js
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const recommendationsRouter = require('./routes/recommendations');
const scrapeRoute = require('./routes/scrape');
const app = express();
const PORT = process.env.PORT || 5000;
// Middleware
app.use(cors({
origin: ['http://localhost:3000', 'https://beauty-finder.vercel.app']
}));
app.use(express.json());
// Routes
app.use('/api/recommendations', recommendationsRouter);
app.use('/api', scrapeRoute);
// Error handling
app.use((err, req, res, next) => {
console.error('Server Error:', err);
res.status(500).json({
error: 'Internal server error',
message: process.env.NODE_ENV === 'production' ? 'Something went wrong' : err.message
});
});
module.exports = app;
// Start server if not in production
if (process.env.NODE_ENV !== 'production') {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`- Recommendations API: http://localhost:${PORT}/api/recommendations`);
console.log(`- Scraping API: http://localhost:${PORT}/api/scrape`);
});
}
vercel.json
{
"version": 2,
"builds": [
{
"src": "api/index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/api/(.*)",
"dest": "api/index.js"
}
]
}
I updated the path on vercel.json, and now the error is @Anay-208 | Ping on replies



FelipeOP
I'm still getting the same error after removing builds @Anay-208 | Ping on replies
in src, you've
/api/
at the start instead of /
if that still doesn't works, check vercel logs

FelipeOP
Okay
Should my .env be inside api/ ?
I'm getting
APIFY_TOKEN is not defined. Please set it in your environment
@Anay-208 | Ping on replies . It's defined on .env
Have you added environment variables in vercel?

FelipeOP
I have
@Anay-208 | Ping on replies


try redeploying
Answer

FelipeOP
Okay

FelipeOP
It worked! Thanks!