Set up your server on Vercel platform for seamless deployment

Currently, I am following a tutorial by CJ, where he demonstrates deploying his server using now.

However, the tutorial is now outdated as now has been replaced with vercel. I am unsure about how to proceed with vercel. Can someone provide guidance on this process? I have both a backend and a frontend. CJ's method involved deploying the server with now, and another helpful tutorial also makes use of now.

To access my server at velcer: click here for the vercel app

vercel json

{
    "name": "my-mongodb-api",
    "builds": [{ "src": "index.js", "use": "@now/node-server" }],
    "version": 2,
    "env": {
      "MONGODB_URI": "@my-mongodb-uri"
    }
  }

package json

{
  "name": "vermittlungsprojekt",
  "version": "1.0.0",
  "description": "Kunstmuseum Basel",
  "main": "index.js",
  "dependencies": {
    "bad-words": "^3.0.3",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-rate-limit": "^5.1.3",
    "monk": "^7.3.1",
    "morgan": "^1.10.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.4"
  },
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "author": "Luis M Luethi",
  "license": "ISC"
}

server code

// start server: npm run dev
// 

const express = require("express");
const cors = require('cors');
const monk = require("monk");
const Filter = require('bad-words');
const rateLimit = require("express-rate-limit");

 


const app = express();


const db = monk( 'localhost/beitraege'); /*process.env.my-mongo-uri ||*/
const posts = db.get("post");
const filter = new Filter();


app.use(cors());
app.use(express.json());

app.get("/", (req, res) => {
       res.json({
           message: "POST"
       });
});

app.get("/beitraege", (req, res)=> {
    posts
        .find()
        .then(posts => {
            res.json(posts)
        })

})

function isValidPost(post){
    return post.name && post.name.toString().trim() !== "" &&
        post.content && post.content.toString().trim() !=="";
}

app.use(rateLimit({
    windowMs: 30 * 1000, // 30 sec
    max: 1 // limit each IP to 100 requests per windowMs
  }));

app.post("/beitraege", (req, res) => {
    if (isValidPost(req.body)){
        const post = {
            name: filter.clean(req.body.name.toString()),
            content: filter.clean(req.body.content.toString()),
            created: new Date()
        };
        //console.log(post);
        posts
            .insert(post)
            .then(createdPost => {
                 res.json(createdPost);
                  })
            .catch(err => {
            return Promise.reject();
        })
        
    }else {
        res.status(422);
        res.json({
           message: "Hey, Titel und Inhalt werden benötigt!" 
        });
    }
});

app.listen(5000, () => {
  console.log('Listening on http://localhost:5000');
});

Answer №1

After deploying your code to Vercel, there are a few important steps to follow:

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

The expectation is that the index.js referenced in the package.json file should be located within the ./src directory.

  • Ensure the server runs on port 80.
  • Test the server for any issues on your local machine before deployment.
  • If you're utilizing the builds option in the vercel.json file, make sure all dependencies like node_modules are uploaded to Vercel by deploying files through vercel-cli, or using a pipeline or CI process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Azure SDK to send an email

In my Node.js project, I am currently utilizing azure-graph: const MsRest = require('ms-rest-azure'); const credentials = await MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId, { tokenAudience: 'graph' } ...

Why does the RethinkDB query keep returning null even when the data is present?

Having some trouble with rethinkDB while trying to retrieve data by username using the filter function. Despite the data being present, rethinkDB is returning null. //Define Your Api//Define Your Api import express from 'express'; import r f ...

Setting up a connection to MongoDB on a local network using express and mongoose

As I set up a server with express and mongoose, my goal is to make it accessible on other devices within my local network. To achieve this, I configured the bind_ip variable to 0.0.0.0 in the Mongodb configuration file. const connection = mongoose .co ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

Strategies for hiding my true video streaming server in Node.js from viewers?

I'm currently developing a Video on Demand project in NodeJS that offers customers the option to purchase or subscribe to videos. These videos are hosted on a Streaming Server (similar to Red5) which includes features like interactive player, adaptiv ...

Could not locate the <command> within the docker container causing npm script to fail with sh: 1 error

Query Whenever I execute the command npm run start:debug within a docker container, I encounter this particular error: # npm run start:debug > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6001100920504e504e50">[email ...

Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks: https://i.stack.imgur.com/klPYV.png This is the middleware I am using: import { NextResponse, NextRequest } from "next/server"; export async functi ...

Installing nodejs will cause issues with the successful installation of Npm

I recently started using Node.js and I used the following command to install it: sudo apt-get install -y nodejs Usually, npm is automatically installed along with Node.js. However, when I checked the version of npm, I received this output: https://i.sta ...

How to efficiently initialize a Next.js app with Phusion Passenger while triggering the production build using a specific file?

In most cases, a Next.js application is launched by using the command npm run start after compiling it with npm run build. I am unable to start it using a command because my web server stack (Phusion Passenger) requires a specific startup script. https:// ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

The server redirected the request from a post route to a get route

I have a Node.js application and I am interested in redirecting a post request to a get request within the app. This is the code snippet for the application: const express = require('express'); const app = express(); app.get('/get-route& ...

Automatically convert TypeScript packages from another workspace in Turborepo with transpilation

I have set up a Turborepo-based monorepo with my primary TypeScript application named @myscope/tsapp. This application utilizes another TypeScript package within the same repository called @myscope/tspackage. For reference, you can view the example reposit ...

React App's proxy configuration to connect with an Express server for PassportJS authentication is currently malfunctioning

After spending some time trying to configure a proxy for my React app to connect with my Express backend, using passportjs for Google social authentication, I encountered an issue. The React development server is running on PORT 3000 while the Express ser ...

What is the process for converting a buffer into an image file?

I am struggling with retrieving images stored in GridFS and converting them into a buffer using the code I have written. However, I'm unable to find proper documentation on how to render an image from this buffer within the MEAN stack environment. My ...

The issue arises with loading data from the server due to lack of definition of Mongo

I am experiencing a console bug and need assistance. It seems that there is an issue with loading data from the server as I am getting an error stating "Mongo is not defined." C:\Users\Robert\Desktop\FINISH\node_modules\mongod ...

Is it possible to have nullable foreign keys using objectionjs/knex?

It seems like I'm facing a simple issue, but I can't quite figure out what mistake I'm making here. I have a table that displays all the different states: static get jsonSchema() { return { type: 'object', propert ...

When I try to make an on-demand revalidation API call on Vercel, it takes so long that it ends up timing

Inspired by Kent C. Dodds, I have created a blog using Github as my Content Management System (CMS). All of my blog content is stored in the same repository as the code, in mdx format. To streamline the process, I set up a workflow that detects changes i ...

Step-by-step guide on setting up and utilizing the eth-auth (ethauth-server) library

Can you explain the purpose and usage of the eth-auth library? Additionally, could you provide instructions on how to incorporate the ethauth-server npm library into a node.js project? ...

Saving a file with its original filename using ng file upload on the server: Tips and tricks

I am having an issue with ng file upload where my files are being saved on the server with a different file name. I want them to be saved with their original file name and correct extension (.jpg, .pdf). Here is my code snippet. Controller: $scope.uploadP ...

The most common method for incorporating subdomains (such as the jp in jp.sweet-website.org) into nodejs applications

The current versions are Express 4.10.2 and Node 6.5.0 How can I create a subdomain for my website? I am looking to include a Japanese version of my site that will be accessible through http://jp.site-in-question.run in addition to the default English ...