Express.js apps with Netlify Functions

Devamakesh
2 min readApr 9, 2021

What is Netlify?

Netlify is a hosting service for the programmable web. It understands your documents and provides an API to handle atomic deploys of websites, manage form submissions, inject JavaScript snippets, and much more.

Express.js

An API is always needed to create mobile applications, single-page applications, use AJAX calls, and provide data to clients. A popular architectural style of how to structure and name these APIs and the endpoints are called REST(Representational Transfer State).

server.js

import { start } from ‘./src/server’

start()

This the main file to execute the program.

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

.prettierrc.js

module.exports = {

semi: false,

singleQuote: true

}

Prettier config file that makes the compiler like a semi, single quote.

Babel

ESLint allows custom parsers. This is great but some of the syntax nodes that Babel supports aren’t supported by ESLint. When using this plugin, ESLint is monkey patched and your code is transformed into code that ESLint can understand. All location info such as line numbers, columns are also retained so you can track down errors with ease.

Netlify-lambda

This is an optional tool that helps with building or locally developing Netlify Functions with a simple webpack/babel build step. For function folders, there is also a small utility to install function folder dependencies.

The goal is to make it easy to write Lambdas with transpiled JS/TypeScript features and imported modules.

Serverless-http

This module allows you to ‘wrap’ your API for serverless use. No HTTP server, no ports or sockets. Just your code in the same execution pipeline you are already familiar with.

Install netlify, babel and serverless-HTTP

npm install netlify-lambda babel serverless-http

Script in package.json

“scripts”: {npm install netlify babel serverless-http

“build”: “babel src — out-dir dist”,

“start”: “node dist/index.js”,

“deploy”: “netlify-lambda build”

},

Script to build and deploy the API in Netlify

The script that can make the test run is npm run build

index.js

Server to deploy the app by serverless HTTP.

const express = require(‘express’)

const app = express()

const serverless = require(‘serverless-http’)

const connectDB = require(‘./src/config/db’)

const bodyParser = require(‘body-parser’)

const router = require(‘./src/index’)

app.use(bodyParser.json())

app.use(‘/.netlify/functions/server’, router) // path must route to lambda

module.exports.handler = serverless(app)

module.exports = app

Deploy:

Connect git repo to netlify , commit all change and push to the main branch. Enable auto build and make the automation.

Test your API using postman

--

--