Deploying to Netlify
Overview
In this guide, you will set up and deploy a serverless Node.js application to Netlify. The application will expose a REST API and use Prisma Client to handle fetching, creating, and deleting records from a database.
Netlify is a cloud platform for continuous deployment, static sites, and serverless functions. Netlify integrates seamlessly with GitHub for automatic deployments upon commits. In this guide, you will use this approach to create a CI/CD pipeline that deploys your application from a GitHub repository.
The application has the following components:
- Backend: Serverless Node.js REST API with resource endpoints that use Prisma Client to handle database operations against a PostgreSQL database (e.g. hosted on Heroku).
- Frontend: Static HTML page to interact with the API.
The focus of this guide is showing how Prisma integrates with Netlify. The starting point will the Prisma Netlify example which has a couple of REST endpoints preconfigured as serverless functions and a static HTML page.
With Netlify, the fundamental building block is a Site. Sites are typically connected to a Git repository and have a publicly accessible URL that looks like https://site-name.netlify.com
. In this guide, you will connect a GitHub repository to a Netlify site.
Throughout the guide you'll find various checkpoints that enable you to validate whether you performed the steps correctly.
Prerequisites
- GitHub account
- Hosted PostgreSQL database and a URL from which it can be accessed, e.g.
postgresql://username:password@your_postgres_db.cloud.com/db_identifier
(you can use Heroku, which offers a free plan). - Netlify account connected to your GitHub account (Netlify will need access to the repository you will create as part of this guide).
- Netlify CLI installed.
- Node.js installed.
- PostgreSQL CLI
psql
installed.
Prisma workflow
Prisma supports different workflows depending on whether you integrate with an existing database or create a new one from scratch. Regardless of the workflow, Prisma relies on the Prisma schema, i.e. schema.prisma
file.
This guide starts with an empty database created with plain SQL and looks as follows:
- Define the database schema using SQL.
- Run
prisma introspect
locally which will introspect and populate theschema.prisma
with models based on the database schema. - Run
prisma generate
which will generate Prisma Client based on the Prisma schema.
1. Fork the deployment-example-netlify
repository
Go to deployment-example-netlify
and Fork the repository by clicking on the fork button on the top right corner:
By forking, you create a copy of the repository to which you will be able to commit your changes. Later in the guide, you will connect the forked repository to Netlify so that changes are automatically built and deployed.
Checkpoint: After cloning you should see the forked repository in your account, i.e. https://github.com/YOUR_GITHUB_USERNAME/deployment-example-netlify
2. Clone the fork and install dependencies
Open your terminal, navigate to a location of your choice and clone your fork of the deployment-example-netlify
:
$git clone git@github.com:YOUR_GITHUB_USERNAME/deployment-example-netlify.git
After cloning the repository, install the dependencies:
$cd deployment-example-netlify$npm install
Checkpoint: ls -1
should show:
$ls -1$README.md$functions$netlify.toml$node_modules$package.json$prisma$public$schema.sql
3. Set the DATABASE_URL environment variable locally
Set the DATABASE_URL
environment variable locally so you can create the database schema and Prisma can access the database to introspect:
$export DATABASE_URL="postgresql://__USER__:__PASSWORD__@__HOST__/__DATABASE__"
Note: you will need the
DATABASE_URL
environment variable for the subsequent steps. Set it in all terminal sessions related to this project.
You need to replace the uppercase placeholders with your database credentials, e.g.:
$postgresql://janedoe:randompassword@yourpostgres.compute-1.amazonaws.com:5432/yourdbname
4. Create the database schema
To create your database schema, run the schema.sql
from the example code as follows:
$psql $DATABASE_URL -f schema.sql
Checkpoint: psql $DATABASE_URL -c "\dt"
should show the list of tables:
List of relationsSchema | Name | Type | Owner-------+---------+-------+----------------public | Post | table | janedoepublic | Profile | table | janedoepublic | User | table | janedoe
Congratulations, you have successfully created the database schema.
5. Introspect the database
Introspect the database with the Prisma CLI:
$npx prisma introspect
Prisma will introspect the database defined in the datasource
block of the Prisma schema and populate the Prisma schema with models corresponding to the database tables.
Checkpoint: Open prisma/schema.prisma
and ensure there are three models: Post
, Profile
, and User
.
6. Commit the Prisma schema to the repository
The result of prisma introspect
is the schema.prisma
Prisma schema file.
Since the Prisma schema is used to generate Prisma Client, commit it to your repository so that Prisma Client can be generated when Netlify builds the project:
$git commit prisma/schema.prisma -m 'Add Prisma schema'
7. Netlify login
Make sure you're logged in to Netlify with the CLI:
$netlify login
This will allow you to create a Netlify site and connect it to a repository from the terminal.
Checkpoint: netlify status
should show your username:
$netlify status$──────────────────────┐$ Current Netlify User │$──────────────────────┘$Name: your name$Email: your@email.com$Teams:$ ....
8. Configure continuous deployment to Netlify
From the repository's folder, run netlify init
to configure a new Netlify site:
You will be prompted with configuration options:
- Select
Create & configure a new site
- If prompted to select your team, pick the one in which Netlify will create the site
- Give the site a unique name
- Your build command:
npm run build
- Directory to deploy:
public
Checkpoint: The Netlify CLI should output the following:
Site CreatedAdmin URL: https://app.netlify.com/sites/YOUR_SITE_NAMEURL: https://YOUR_SITE_NAME.netlify.com
Note: You can change the build configuration via the
netlify.toml
file and the site name from the Netlify admin UI.
Enable Netlify Build Plugins Beta
Due to a bug with the Prisma engine binary not getting packaged for deployment to Lambda, it is necessary to enable the Netlify Build Plugins Beta.
To do so, go to https://app.netlify.com/enable-beta and enable it for the site you just deployed.
9. Expose the DATABASE_URL environment variable to functions
Since Prisma will connect to the database from your serverless functions, you need to expose the DATABASE_URL
to the backend functions. This is typically done from the Netlify UI. To do, open the Netlify admin UI for the site. You can do so directly with the Netlify CLI as follows:
$netlify open --admin
Once open, go to Site settings:
Navigate to Build & deploy in the sidebar on the left and then select Environment:
Create a variable with the key DATABASE_URL
and set the value with your PostgresSQL URL.
Note: It's considered best practice to keep secrets out of your codebase. If you open up the
prisma/schema.prisma
file, you should seeenv("DATABASE_URL")
in the datasource block. By setting an environment variable you keep secrets out of the codebase.
10. Deploy the app
Your project is now ready for deployment
You can now use git push
to push the commit with the Prisma schema. This will trigger a netlify build.
Checkpoint: Call the API status endpoint:
$curl https://YOUR_SITE_NAME.netlify.com/.netlify/functions/status
The call should return: {"up":true}
11. Test your deployed application
Open the site from the command line:
$netlify open:site
This will open the static frontend that you deployed.
The URL should like this: https://YOUR_SITE_NAME.netlify.com
.
The four buttons allow you to make requests to the REST API and view the response:
- Check API status: Will call the REST API status endpoint that returns
{"up":true}
. The implementation code is infunctions/index.js
- Seed data: Will delete all database records and load the database with test data
users
,profiles
, andposts
. Returns the created users. The implementation code is infunctions/seed.js
- Load users with profiles: Will load all
users
in the database with their relatedprofiles
. The implementation code is infunctions/getUsers.js
- Load Posts: Will load
posts
and their relatedauthors
. The implementation code is infunctions/getPosts.js
For example, calling seed data should show the following:
Summary
Congratulations! You have successfully deployed the application to Netlify.
For more insight into Prisma Client's API, look at the function handlers in the functions/
folder.
Generally, when using a FaaS (function as a service) environment to interact with a database, it's beneficial to pool DB connections for performance reasons. This is because every function invocation may result in a new connection to the database (this is not a problem with a constantly running node.js server). For more information on some of the solutions, you may want to look at our general FaaS guide.