Setting up a boilerplate application with Express, PostgreSQL, Sequelize and React
Setting up a boilerplate application step by step is a tedious work but once done, makes building future projects easier. For my project template I will use JavaScript tech stack: Node and Express bind the web backend together, PostgreSQL serves as the database, and React makes the frontend that the user sees and interacts with.
Project layout
my-project/-- client/
---- index.js <-- entry point for client JavaScript
-- node_modules/
-- public/--db/
----index.js <-- entry point for database connection --apiRoutes/
----index.js <-- db setup
----users.js <-- db table user
----blogposts.js. <-- db table blogposts-- server/
---- index.js <-- entry point for server
-- .gitignore <-- files etc. to ignore when you make a commit
-- package.json <-- stores the names and versions for all the installed packages
Steps to build an application.
Organizing your backend
- Install Node
Node was developed as a JavaScript runtime environment built on Chrome’s V8 JavaScript engine. Node made it possible to start using JavaScript on the server-side. Node’s default package management system, is called npm. It gives access to many reusable Node packages. In order to integrate our stack technologies and run our template application, we will need the following npm modules:
Express: To use Express in your code, you will need the express module
Sequelize : To use Sequelize with Node applications, you also need to add the driver, which is available as an npm module named sequelize-cli
PostgreSQL:To start usingPostgreSQL, we will need to install it from terminal: sudo apt-get install postgresql postgresql-contrib (follow these instructions: https://help.ubuntu.com/community/PostgreSQL)
React: To start using React, we will need two modules: react, react-dom
To test if the installation was successful, you can open the command line and run node -v
to see if it correctly returns the version number. After you have installed Node, you can usenpm
command. In order to create your project folder use npm init
, git init
, and make a .gitignore
file.
From the command line, enter your project folder and run npm init,
which auto-generates package.json
file, that stores dependencies.
In .gitignore
file put files that you do not need on your github account. I suggest : node_modules
bundle.js
bundle.js.map
secrets.js
2. Install Express
Express is a basic framework for building web applications and APIs with a Node server. It provides a simple layer of fundamental web application features that complements Node.
npm install — save express
3. Middleware in Express.js
Middleware functions are functions that have access to the HTTP request and response objects, and also the next middleware function in the web application’s request-response cycle.
npm install — save morgan
4. Install body parser
body-parser extract the entire body portion of an incoming request stream and exposes it on req. body
npm install — save body-parser
5. Routing in Express.js
Express supports methods that correspond to all HTTP request methods: get, post, and so on. Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.
const router = require(‘express’).Router();
router.get('/', function (req, res, next) {//your code}
6. Serving static assets with Express.js
One preferable approach is to serve all static files from one directory eg. public
directory. In this directory we move bundle.js, style.css
, place them as well as any other static files in the and use the following approach to statically serve all files out of public
:
app.use(express.static(__dirname + '/public'));
app.get('*', function(req, res){
res.sendfile(__dirname + '/public/index.html');
});
7. Start server
In order to check if the server is set up properly use the command node inedx.js
. Although we have a proper logic, we are not sending any index.html yet. We need to create public folder and index.html.
Setting up database
Start from installing PostgreSQL and sequelize.
$ npm install — save pg pg-hstore # Postgres
From your terminal create database:
createdb template_db
Create folder db and initialize Sequelize instance.
const { Sequelize, Model, DataTypes } = require(“sequelize”);// Option 1: Passing a connection URI //https://sequelize.org/master/manual/getting-started.htmlconst sequelize = new Sequelize(‘postgres://localhost:5432/yourdbname’) // Example for postgresconst User = sequelize.define(“user”, {
name: DataTypes.TEXT,
});module.exports = sequelize;
At the end synchronize your database. The best practice is to sync your database before the server starts. In order to do so, add the code below to index.js (server folder).
(... code omitted)
const sequelize = require('./db/db.js')(... code omitted)
const startServer = () => {const server = app.listen(process.env.PORT || PORT, () =>
console.log(`Listening on ${PORT}`))
}
;(async () => {
await sequelize.sync()
console.log(‘db sync’)
})(startServer())
Synchronization tips:
User.sync()
- This creates the table if it doesn't exist (and does nothing if it already exists)User.sync({ force: true })
- This creates the table, dropping it first if it already existedUser.sync({ alter: true })
- This checks what is the current state of the table in the database (which columns it has, what are their data types, etc), and then performs the necessary changes in the table to make it match the model.
Organizing your frontend
1. React
React, is an open source library that came out of Facebook. It is the answer for the need of having more control over behavior of an application on the client side. The creators of React, came up with the idea that an application may be composed by using components.
If you read something about React, one thing that it brought up is Virtual DOM — abstraction, updates only the parts that has to be re-rendered. In order to develop with React, you need Babel modules for converting ES6 and JSX to suitable JavaScript for all browsers. If you are interested in React App without Babel and Webpack, I recommend further reading here: .
The modules needed to get Babel working are: babel-core, babel-loader for transpiling JavaScript files with Webpack, babel-preset-env, babel-preset-react, and babel-preset-stage-2
Webpack modules will help bundle the compiled JavaScript, both for the client-side and server-side code. Below you will find all modules that we need to set up our template. You may use webpack-cli’s
init
command that will ask you a couple of questions before creating a configuration file.
//npx webpack-cli init"dependencies": {
"@babel/preset-env": "^7.8.7",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"morgan": "^1.9.1",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-hot-loader": "^4.1.2",
"react-router-dom": "^5.1.2"
},"devDependencies": {
"@babel/core": "^7.8.7",
"@babel/preset-react": "^7.8.3",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.17.3",
"webpack": "^4.20.2",
"webpack-cli": "^3.1.1",
"webpack-dev-middleware": "^3.1.2",
"webpack-hot-middleware": "^2.22.1",
"webpack-node-externals": "^1.7.2"}
2. Create client folder
Inside client folder, create index.js — an entry for webpack.
import React from ‘react’;
import ReactDOM from ‘react-dom’;ReactDOM.render(
<div>Hello, world!</div>,
document.getElementById(‘app’) // make sure this is the same as the id of the div in your index.html
)
3. Create public folder
Inside client folder, create index.html and add script with bundle.js.
4. Configure webpack.config.js
module.exports = {
entry: ‘./client/index.js’, // assumes your entry point is the index.js in the root of your project folder
mode: ‘development’,
output: {
path: __dirname,
filename: ‘./public/bundle.js’
// assumes your bundle.js will also be in the root of your project folder
}, devtool: ‘source-maps’,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: ‘babel-loader’
}}]
}}
5. Customize your package.json and add your scripts
"start": "node server",
"start-dev": "webpack -w & nodemon index.js"
Final version
We can write and build static web pages with this setup! The complete setup may be downloaded from the repository listed below. Run the following commands from your terminal:
git remote add template https://github.com/kwegorek/basic_template_react.git
git fetch template
git merge template/master