Set up Express.js in Node.js and build a small application with Nodemon, express-generator, and dotenv libraries

set-up-express-node-js-with-nodemon-express-generator-dotenv

In this tutorial you will set up a new Express.js application with some commonly used libraries like nodemon and dotenv.

Let’s assume you’ve already installed Node.js, as a next step we will create a new directory for your Express.js application.

In a terminal type the following 2 commands:

$ mkdir myExpressApp
$ cd myExpressApp

Now type the npm init command in your terminal to create a package.json file for your application. For more information on package.json works, see npm’s package.json documentary.

npm init

This command prompts you for a number of things, such as the package name, version of your application, description, test command, git repository, etc. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:

entry point: (index.js)

Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name. When asked Is this OK? (yes) type yes.

Now install Express in your app directory and save it in the dependencies list. For example:

npm install express

Express-generator

To install express-generator, to create an application skeleton, run the following command:

npm install -g express-generator

For more information take a look at npm’s express-generator documentary.

The express-generator can be further configured with the following commands:

    --version        output the version number
-e, --ejs            add ejs engine support
    --pug            add pug engine support
    --hbs            add handlebars engine support
-H, --hogan          add hogan.js engine support
-v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
    --no-view        use static html instead of view engine
-c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
    --git            add .gitignore
-f, --force          force on non-empty directory
-h, --help           output usage information

For the views, let’s choose ejs for this application, therefore run this command in your terminal to create the application skeleton:

express --view=ejs

Now you should see the following directory structure:

.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.ejs
    └── index.ejs

7 directories, 8 files

Install dependencies with the npm install command:

npm install

Start your Express.js app at http://localhost:3000/ with the npm start command:

npm start

If you wish to change the port, go to bin/www or you can use an environment file later in this tutorial to configure the port.

Nodemon

So far, you are able to start your application by running the npm start script. The only remaining concern is that you have to restart the app every time you change it. You can change this behavior with an always-running node process. To remedy this, install the commonly used nodemon library on the command line:

npm install nodemon

Next, in your package.json file add a new script, to start your app using nodemon:

"scripts": {
    "start": "node ./bin/www",
    "dev": "npx nodemon app.js -e js,ejs,html,css"
},

Using the script above your app will restart, whenever you save files with the specified extensions. You can now start your app with this command (instead of npm start):

npm run dev

Environment variables in Node.js

It is crucial to set data like private API keys and user credentials like password, username, etc. as environmental variables, but without exposing them in the source code. Therefore, let’s put environment variables in a dedicated file that is safe from external access. The .env file lets you set Node.js environment variables. On the command line, in your project’s root folder, create a .env file:

touch .env

Now you can place any key value pair that you don’t want in your source code in this new file, for instance an API key:

API_KEY=mySecretApiKey123

dotenv is another helpful library to make environmental variables accessible in the source code. First, install it on the command line as a normal dependency:

npm install dotenv

Second, import it into your app.js or index.js file to initialize it. The environment variable from your .env file is now accessible in your source code.

require('dotenv').config()
console.log('My API key: ', process.env.API_KEY);

An even better option is to create a new module in a file named config.js. in the root directory of your app, next to app.js. Then copy and paste the following code into the file:

// config.js
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
  apiKey: process.env.API_KEY,
  anotherApiKey: process.env.ANOTHER_API_KEY
};

Then in your app.js file you can simply import the module and use credentials like API keys:

// app.js
const { apiKey, anotherApiKey } = require(‘./config’);

And that’s it. Now you have a running express.js application that restarts easily with nodemon, whenever you change files, and that includes the dotenv library to store your credentials safely in an environment file.

Leave a Reply

Your email address will not be published. Required fields are marked *