Persiapan
- Install NodeJs
- Install MongoDB Community
- Buat Database MongoDB bernama mongoose_basics
Buat Project
mkdir -p jwt-node-auth/{controllers/users.js,models/users.js,routes/index.js,routes/users.js} cd jwt-node-auth touch utils.js && touch config.js && touch index.js
Struktur direktori:
root ├── .env ├── config.js ├── controllers │ └── users.js ├── index.js ├── models │ └── users.js ├── routes │ ├── index.js │ └── users.js ├── utils.js
Installasi Dependensi
npm init --yes npm install express body-parser bcrypt dotenv jsonwebtoken mongoose --save npm install morgan nodemon cross-env --save-dev
Fungsi Dependensi
- body-parser: This will add all the information we pass to the API to the
request.body
object. - bcrypt: We’ll use this to hash our passwords before we save them our database.
- dotenv: We’ll use this to load all the environment variables we keep secret in our
.env
file. - jsonwebtoken: This will be used to sign and verify JSON web tokens.
- mongoose: We’ll use this to interface with our mongo database.
Development Dependensi
- morgan: This will log all the requests we make to the console whilst in our development environment.
- nodemon: We’ll use this to restart our server automatically whenever we make changes to our files.
- cross-env: This will make all our bash commands compatible with machines running windows.
Membuat Enviroment Variabel(.env)
.env
JWT_SECRET=addjsonwebtokensecretherelikeQuiscustodietipsoscustodes MONGO_LOCAL_CONN_URL=mongodb://127.0.0.1:27017/node-jwt MONGO_DB_NAME=auth-with-jwts
config.js
module.exports = { development: { port: process.env.PORT || 3000 } }
index.js
require('dotenv').config(); // Sets up dotenv as soon as our application starts const express = require('express'); const logger = require('morgan'); const bodyParser = require('body-parser'); const app = express(); const router = express.Router(); const environment = process.env.NODE_ENV; // development const stage = require('./config')[environment]; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); if (environment !== 'production') { app.use(logger('dev')); } app.use('/api/v1', (req, res, next) => { res.send('Hello'); next(); }); app.listen(`${stage.port}`, () => { console.log(`Server now listening at localhost:${stage.port}`); }); module.exports = app;

Referensi: