Learn Javascript

Servers

Hosting a Javascript application, including security and production

slides | md

Server options

Web host Static Dynamic Node PHP Python database .env Live Cost
Github Pages free
Localhost free
Shared host $
VPS hosting $$
glitch.com ? free(mium)
vercel.com free(mium)

Others
https://codepen.io/
https://codesandbox.io/
https://stackblitz.com/

Notes: Databases require PHP or node. React or Next projects can be built for static

Host a node app on Vercel

  1. Add a vercel.json file
{
	"version": 2,
	"name": "YOUR_APP_NAME",
	"builds": [{
		"src": "./server.js",
		"use": "@vercel/node"
	}],
	"routes": [{
		"src": "/(.*)",
		"dest": "/server.js"
	}]
}
  1. Export your application
// server.js
var express = require('express');
var app = express();
// routers
// middleware
// start server
// finally ...
module.exports = app;
  1. Continue with this tutorial: Deploy Node.js application to Vercel

Running node on a server

Use pm2 to monitor, manage, and restart your node/express app.

Securing information

Never commit secure information (database passwords, API keys, etc.) to git.

  1. Use .gitignore to prevent adding secure files to git
  2. If the secret information is required for your project then you will also need to add the secret file to your server

See below for tutorials.

Securing information with .gitignore

  1. Create a new file for the secret information.
// secure.js
let key = 12345;
  1. Import the file (before your other code!)
<!-- index.html -->
<script src="secure.js"></script>
<script>console.log(key)</script>  
  1. Create a .gitignore file in the root of your project. Add the name of the secret file on a new line.
# .gitignore
passwords.js
  1. Commit the .gitignore file and then git will not track the file containing your secret information.

*Your file will only run on your computer

Keep your passwords safe with .env

  1. Create a .env in the project root and add secure information
USER="admin"
PASS="123456"
  1. Create a .gitignore file in your project root. Add the .env.
node_modules
.DS_Store
.env
  1. Install dotenv
npm install dotenv
  1. Import the dotenv module, which loads variables from .env file.
// import package
require('dotenv').config()
// vars are now available
console.log(process.env.USER)

Keep your passwords safe with .env (part 2)

  1. (optional) Make a copy of the file to your server (e.g. Vercel) with the correct contents. This also allows different (ahem, more secure) DB user/pass on your server vs. your localhost
  2. (optional) Create a .env.example file with placeholder information so you can duplicate, rename, and then replace the values on your server

Presentation comments ...