Deploying a full-stack web app
This guide is for deploying node apps with a React/SPA frontend and an Express backend.
Add production routes for the server
Import Path in server.ts
import * as Path from 'node:path'
Make sure the following is included in your server.ts
file too(underneath your other routes)
if (process.env.NODE_ENV === 'production') {server.use(express.static(Path.resolve('public')))server.use('/assets', express.static(Path.resolve('./dist/assets')))server.get('*', (req, res) => {res.sendFile(Path.resolve('./dist/index.html'))})}
Add custom build and start scripts
Add these scripts to your package.json
:
"render:build": "npm install && npm run build && npm prune --omit=dev","render:start": "node dist/server.js"
Sign in to Render and create a Web Service
Go to render.com and sign in.
Click “New > Web Service”.
Authenticate your GitHub account if prompted.
You should see a list of repos to choose from. Select the one you want to deploy.
Choose branch and runtime
- Choose Node as the environment
- Select the branch you want to deploy from (Render will auto-deploy from this branch)
- Choose the Free plan!
Then set your commands in the Render service settings:
- Build Command:
npm run render:build
- Start Command:
npm run render:start
Click Deploy Web Service (Don't worry if you see a Failed message for the deploy at this point)
Set environment variables
If you are using a .env
file in your project, there are some extra steps to complete. We use dotenv
for loading environment variables in development, but render uses an Environment tab instead and can generate errors if we try to import dotenv in production.
To solve that replace any instances of import 'dotenv/config'
in your server.ts
or routes files with the following code:
if (process.env.NODE_ENV !== 'production') {import('dotenv').then((dotenv) => dotenv.config()).catch((err) => {console.error('Failed to load dotenv: ', err)})}
Then you can add your env vars from the Environment tab. Click the add button for each new key.
That’s it!
Once your deploy completes, Render will show you the URL to your live site 🎉