Next.js Discord

Discord Forum

Serverless Function to backend

Answered
Felipe posted this in #help-forum
Open in Discord
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.
Answered by Anay-208
try redeploying
View full answer

55 Replies

I already have the project deployed, but when I go on to test the api using ThunderClient, it returns this
sure!
{
  "version": 2,
  "builds": [
    {
      "src": "server.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/api/(.*)",
      "dest": "server.js"
    }
  ]
}
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
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*
I don't know If I'm doing it right, my professor said we could host it on vercel. Maybe I can't?
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
@Black carpenter ant what it does?
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
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 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
Okay, I'll try it!
Thanks guys! I'll send another message if I have other issues!! Thanks a lot!
@Anay-208 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
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
Can you share your index.js and vercel.json once again?
@Felipe
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
I'm still getting the same error after removing builds @Anay-208
in src, you've /api/ at the start instead of /
if that still doesn't works, check vercel logs
Okay
Should my .env be inside api/ ?
I'm getting APIFY_TOKEN is not defined. Please set it in your environment @Anay-208 . It's defined on .env
Have you added environment variables in vercel?
I have
@Anay-208
try redeploying
Answer
Okay
It worked! Thanks!