Host your existing MERN app on Vercel

Why host MERN apps on Vercel?

Example Repo

Setting up

yarn add vercel -D vercel login

Setting up environment variables

MONGO_URI
AWS_ACCESS_KEY
AWS_SECRET_KEY
AUTH_ZERO_DOMAIN
AUTH_ZERO_CLIENT_ID
vercel secrets add [secret-name] [secret-value]

Vercel Serverless functions

yarn add dotenv mongodb morgan aws-sdk

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();
};

Adapting the Front-End

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

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

Conclusion

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