Host your existing MERN app on Vercel

Why host MERN apps on Vercel?

However, if you don’t have the time or ressources for such a big migration, you can still get a lot of benefits like preview deployments and serverless functions if you host your MERN app on Vercel. In this tutorial, we will show you how to adapt such an application to be hosted on Vercel’s Cloud. This tutorial assumes a intermediate level of understanding and aims at giving an idea of how the process works.

Example Repo

Setting up

yarn add vercel -D vercel login

Once you are logged in, change your start command in the root Package.json to use the vercel cli instead:

You should now be able to run the application for a first time by calling the start command:

You will be prompted to create a new project. Here you can accept the default settings as Vercel is able to detect that this is a create-react-app repo. The good news is that now we have our Front-End running locally and deployable to Vercel.

Setting up environment variables

MONGO_URI
AWS_ACCESS_KEY
AWS_SECRET_KEY
AUTH_ZERO_DOMAIN
AUTH_ZERO_CLIENT_ID

Luckily, Vercel offers a way to set environment variables and protect them nicely. As always, treat all your environment variables with care and avoid having them committed in source code. Instead we can use the Vercel CLI command to have them directly passed to our hosted application:

vercel secrets add [secret-name] [secret-value]

This should be done for all env variables that our application depends on. Please notes that the secrets will be converted to lowercase and should also be converted in your code. After this is done we can move on into adpating the code to use Vercel Serverless functions.

Vercel Serverless functions

yarn add dotenv mongodb morgan aws-sdk

This is normally a good time to decide if you need all those dependencies and refactor some areas of your backend to simplify it. After this we are ready to start building out our serverless functions. From analysing the repo we can make out that there is a REST api to fetch clothes and also a file upload feature. We will focus for now on building out the clothing routes.

Let’s move the aws and mongo folder to the root of the repo. This will make the database available outside the server folder that will soon be removed.

Creating the API folder structure.

const MongoClient = require("../mongo/client");
const { ObjectId } = require("mongodb");

export default async (req, res) => {
const client = await MongoClient();
await client.connect();
const db = client.db("DriveThruCloset");

const { method } = req;

switch (method) {
case "GET":
let getResponse = await db.collection("clothing").find({}).toArray();
res.status(200).json(getResponse);
break;
case "POST":
const { name, description, type } = req.body;
const { filename } = req.file;

let postResponse = await db
.collection("clothing")
.insert({ name, description, filename, type });
res.status(200).json(postResponse);
break;
case "DELETE":
const { _id } = req.body;

let deleteResponse = await db
.collection("clothing")
.deleteOne({ _id: ObjectId(_id) });
res.status(200).json(deleteResponse);
break;
default:
res.setHeader("Allow", ["GET", "PUT"]);
res.status(405).end(`Method ${method} Not Allowed`);
}
client.close();
};

The main difference is that we rely on a switch statement instead of relying on Express to define our methods. This has some advantage and disadvantage but it accomplishes the same as using express. After this is done let’s jump to the last part, adapting the React application.

Adapting the Front-End

let’s find the src/api/api.js file and change the base url to follow our new structure:

const baseurl = `${window.location.origin}/api`;

export default (url, options) => fetch(baseurl + url, options);

Once this is done we now have a happy path establishing the communication between our Front-End and Back-End!

Conclusion

Connect with me on Twitter @gbibeaul if you have any questions on the process!

Originally published at https://frontend-devops.com.

💻 💻 Software Engineer at @filevine . 📖 📖 Instructor for @udacity . ✍️ ✍️ Writer at http://frontend-devops.com