Next.js Discord

Discord Forum

Serverless Function to backend

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

55 Replies

Avatar
I already have the project deployed, but when I go on to test the api using ThunderClient, it returns this
Image
Avatar
Image
Avatar
sure!
{
  "version": 2,
  "builds": [
    {
      "src": "server.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/api/(.*)",
      "dest": "server.js"
    }
  ]
}
Avatar
Okay, I renamed the folder to api
Avatar
Black carpenter ant
i was thinking, you're using basic project, but you're using server.js
Avatar
@Felipe Okay, I renamed the folder to api
Avatar
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
Avatar
@Black carpenter ant *i was thinking, you're using basic project, but you're using server.js*
Avatar
I don't know If I'm doing it right, my professor said we could host it on vercel. Maybe I can't?
Avatar
you can host on vercel
Avatar
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
Avatar
@Black carpenter ant what it does?
Avatar
it uses gemini to send product recommendations to a page, based on the user preferences
Avatar
@Felipe it uses gemini to send product recommendations to a page, based on the user preferences
Avatar
Black carpenter ant
alright, it looks like you haven't shared the server.js yet
Avatar
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`);
  });
}
Avatar
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
Avatar
Okay, I'll try it!
This is the repo, with the api folder and renaming, as suggested @Anay-208 | Ping on replies
Image
Avatar
Can you share your index.js and vercel.json once again?
@Felipe
Avatar
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
Image
Image
Avatar
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
Avatar
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
Avatar
Have you added environment variables in vercel?
Avatar
I have
@Anay-208 | Ping on replies
Image
Avatar
try redeploying
Answer
Avatar
Okay
Avatar
It worked! Thanks!