In this example we are going to create a production server using Heroku.
We will start from 03-github-branch
.
npm install
to install previous sample packages:
npm install
- Create
heroku app
:
-
We need to use an Heroku buildpack. It's a tool to build processes for your preferred language or framework. Right now, we can use heroku-buildpack-static:
-
Use this buildpack in
Settings
tab:
Buildpack url: https://github.com/heroku/heroku-buildpack-static.git
Buildpack url https://github.com/heroku/heroku-buildpack-static.git
- We need
git
to clone the Heroku app repository and works on it:
Check
Deploy
tab for another deploy options.
npm install -g heroku
heroku login
git clone https://git.heroku.com/<heroku-app-name>.git .
Another ways to install Heroku CLI: Download heroku cli Or using npx
- Run build command:
npm run build
-
Copy
./dist
files to new repository. -
Add
static.json
file for deploy config:
./static.json
{
"root": "./"
}
- Result:
|- images
|- js
|- index.html
|- static.json
- Commit and push:
git add .
git commit -m "add static files"
git push
- Open url:
- Sometimes, we need create our custom web server to deploy
static files
and use same server to expose REST API / GraphQL endpoints. We can use nodejs buildpack:
- Remove
heroku-buildpack-static
:
-
Remove
static.json
file. -
Create
public
folder. -
Move
front files
to public folder. -
Copy from
source code repository
>./server/index.js
,./server/package.json
and./server/package-lock.json
files toheroku repository
: -
Add
.gitignore
file:
.gitignore
node_modules
- Result:
|- public/
|---- images
|---- js
|---- index.html
|- .gitignore
|- index.js
|- package-lock.json
|- package.json
- Add a custom REST API endpoint:
./index.js
const express = require('express');
const path = require('path');
const app = express();
const staticFilesPath = path.resolve(__dirname, './public');
app.use('/', express.static(staticFilesPath));
+ app.use("/api/hello", async (req, res) => {
+ res.send("Custom API endpoint");
+ });
const PORT = process.env.PORT || 8081;
app.listen(PORT, () => {
console.log(`App running on http://localhost:${PORT}`);
});
- Deploy it:
git add .
git commit -m "add nodejs + express server"
git push
- Open url:
-
Open
https://<heroku-app-name>.herokuapp.com/api/hello
-
If you want to see logs:
heroku login
heroku logs -a <heroku-app-name>
NOTE: Download heroku cli Use
npm install -g heroku
Or using npx
We are an innovating team of Javascript experts, passionate about turning your ideas into robust products.
Basefactor, consultancy by Lemoncode provides consultancy and coaching services.
Lemoncode provides training services.
For the LATAM/Spanish audience we are running an Online Front End Master degree, more info: http://lemoncode.net/master-frontend