# express-jwt-authenticator

> express-jwt-authenticator is a powerful and secure Node.js authentication package that simplifies the implementation of JSON Web Token (JWT) based authentication in your applications. It provides a robust and flexible solution for user registration, login

Latest version **1.1.15** (published 2024-07-07) · ISC license · 0 weekly downloads

## Install

```sh
npm install express-jwt-authenticator
pnpm add express-jwt-authenticator
yarn add express-jwt-authenticator
bun add express-jwt-authenticator
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.15 |
| Published | 2024-07-07 |
| First published | 2023-07-27 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 157 |
| Unpacked size | 30.8 KB |
| Known vulnerabilities | 0 (+25 in 4 direct dependencies) |
| Install scripts | no |
| Author | Madhukrishna Nipankar |
| Maintainers | madhukrishna |
| Keywords | jwt, authentication, register, login, protect, verify email |

## Links

- npm: https://www.npmjs.com/package/express-jwt-authenticator
- npm.io page: https://npm.io/package/express-jwt-authenticator

## Dependencies (157)

- [ip](https://npm.io/package/ip.md) ^2.0.0
- [ms](https://npm.io/package/ms.md) ^2.0.0
- [qs](https://npm.io/package/qs.md) ^6.11.0
- [has](https://npm.io/package/has.md) ^1.0.3
- [jwa](https://npm.io/package/jwa.md) ^1.4.1
- [jws](https://npm.io/package/jws.md) ^3.2.2
- [bson](https://npm.io/package/bson.md) ^5.4.0
- [depd](https://npm.io/package/depd.md) ^2.0.0
- [etag](https://npm.io/package/etag.md) ^1.8.1
- [glob](https://npm.io/package/glob.md) ^7.2.3
- [mime](https://npm.io/package/mime.md) ^1.6.0
- [once](https://npm.io/package/once.md) ^1.4.0
- [pify](https://npm.io/package/pify.md) ^4.0.1
- [send](https://npm.io/package/send.md) ^0.18.0
- [sift](https://npm.io/package/sift.md) ^16.0.1
- [tr46](https://npm.io/package/tr46.md) ^3.0.0
- [vary](https://npm.io/package/vary.md) ^1.1.2
- [bytes](https://npm.io/package/bytes.md) ^3.1.2
- [chalk](https://npm.io/package/chalk.md) ^2.4.2
- [debug](https://npm.io/package/debug.md) ^2.6.9
- [fresh](https://npm.io/package/fresh.md) ^0.5.2
- [jsesc](https://npm.io/package/jsesc.md) ^2.5.2
- [json5](https://npm.io/package/json5.md) ^2.2.3
- [mpath](https://npm.io/package/mpath.md) ^0.9.0
- [slash](https://npm.io/package/slash.md) ^2.0.0
- [socks](https://npm.io/package/socks.md) ^2.7.1
- [braces](https://npm.io/package/braces.md) ^3.0.2
- [cookie](https://npm.io/package/cookie.md) ^0.5.0
- [dotenv](https://npm.io/package/dotenv.md) ^16.4.5
- [kareem](https://npm.io/package/kareem.md) ^2.5.1
- [lodash](https://npm.io/package/lodash.md) ^4.17.21
- [mquery](https://npm.io/package/mquery.md) ^5.0.0
- [semver](https://npm.io/package/semver.md) ^7.5.4
- [unpipe](https://npm.io/package/unpipe.md) ^1.0.0
- [wrappy](https://npm.io/package/wrappy.md) ^1.0.2
- [accepts](https://npm.io/package/accepts.md) ^1.3.8
- [destroy](https://npm.io/package/destroy.md) ^1.2.0
- [esutils](https://npm.io/package/esutils.md) ^2.0.3
- [express](https://npm.io/package/express.md) ^4.19.2
- [gensync](https://npm.io/package/gensync.md) ^1.0.0-beta.2
- [globals](https://npm.io/package/globals.md) ^11.12.0
- [is-glob](https://npm.io/package/is-glob.md) ^4.0.3
- [methods](https://npm.io/package/methods.md) ^1.1.2
- [mime-db](https://npm.io/package/mime-db.md) ^1.52.0
- [mongodb](https://npm.io/package/mongodb.md) ^5.7.0
- [resolve](https://npm.io/package/resolve.md) ^1.22.2
- [type-is](https://npm.io/package/type-is.md) ^1.6.18
- [yallist](https://npm.io/package/yallist.md) ^4.0.0
- [anymatch](https://npm.io/package/anymatch.md) ^3.1.3
- [bcryptjs](https://npm.io/package/bcryptjs.md) ^2.4.3
- [chokidar](https://npm.io/package/chokidar.md) ^3.5.3
- [ee-first](https://npm.io/package/ee-first.md) ^1.1.1
- [escalade](https://npm.io/package/escalade.md) ^3.1.1
- [has-flag](https://npm.io/package/has-flag.md) ^3.0.0
- [inflight](https://npm.io/package/inflight.md) ^1.0.6
- [inherits](https://npm.io/package/inherits.md) ^2.0.4
- [make-dir](https://npm.io/package/make-dir.md) ^2.1.0
- [mongoose](https://npm.io/package/mongoose.md) ^7.4.1
- [parseurl](https://npm.io/package/parseurl.md) ^1.3.3
- [punycode](https://npm.io/package/punycode.md) ^2.3.0
- [raw-body](https://npm.io/package/raw-body.md) ^2.5.1
- [readdirp](https://npm.io/package/readdirp.md) ^3.6.0
- [saslprep](https://npm.io/package/saslprep.md) ^1.0.3
- [statuses](https://npm.io/package/statuses.md) ^2.0.1
- [call-bind](https://npm.io/package/call-bind.md) ^1.0.2
- [commander](https://npm.io/package/commander.md) ^4.1.1
- [encodeurl](https://npm.io/package/encodeurl.md) ^1.0.2
- [forwarded](https://npm.io/package/forwarded.md) ^0.2.0
- [has-proto](https://npm.io/package/has-proto.md) ^1.0.1
- [ipaddr.js](https://npm.io/package/ipaddr.js.md) ^1.9.1
- [is-number](https://npm.io/package/is-number.md) ^7.0.0
- [js-tokens](https://npm.io/package/js-tokens.md) ^4.0.0
- [lru-cache](https://npm.io/package/lru-cache.md) ^6.0.0
- [minimatch](https://npm.io/package/minimatch.md) ^3.1.2
- [picomatch](https://npm.io/package/picomatch.md) ^2.3.1
- [color-name](https://npm.io/package/color-name.md) ^1.1.3
- [concat-map](https://npm.io/package/concat-map.md) ^0.0.1
- [fill-range](https://npm.io/package/fill-range.md) ^7.0.1
- [iconv-lite](https://npm.io/package/iconv-lite.md) ^0.4.24
- [is-extglob](https://npm.io/package/is-extglob.md) ^2.1.1
- [mime-types](https://npm.io/package/mime-types.md) ^2.1.35
- [negotiator](https://npm.io/package/negotiator.md) ^0.6.3
- [nodemailer](https://npm.io/package/nodemailer.md) ^6.9.14
- [path-parse](https://npm.io/package/path-parse.md) ^1.0.7
- [picocolors](https://npm.io/package/picocolors.md) ^1.0.0
- [proxy-addr](https://npm.io/package/proxy-addr.md) ^2.0.7
- [regenerate](https://npm.io/package/regenerate.md) ^1.4.2
- [whatwg-url](https://npm.io/package/whatwg-url.md) ^11.0.0
- [ansi-styles](https://npm.io/package/ansi-styles.md) ^3.2.1
- [body-parser](https://npm.io/package/body-parser.md) ^1.20.1
- [escape-html](https://npm.io/package/escape-html.md) ^1.0.3
- [fs.realpath](https://npm.io/package/fs.realpath.md) ^1.0.0
- [glob-parent](https://npm.io/package/glob-parent.md) ^5.1.2
- [has-symbols](https://npm.io/package/has-symbols.md) ^1.0.3
- [http-errors](https://npm.io/package/http-errors.md) ^2.0.0
- [media-typer](https://npm.io/package/media-typer.md) ^0.3.0
- [on-finished](https://npm.io/package/on-finished.md) ^2.4.1
- [regjsparser](https://npm.io/package/regjsparser.md) ^0.9.1
- [safe-buffer](https://npm.io/package/safe-buffer.md) ^5.2.1
- [utils-merge](https://npm.io/package/utils-merge.md) ^1.0.1
- [browserslist](https://npm.io/package/browserslist.md) ^4.21.9
- [caniuse-lite](https://npm.io/package/caniuse-lite.md) ^1.0.30001517
- [content-type](https://npm.io/package/content-type.md) ^1.0.5
- [finalhandler](https://npm.io/package/finalhandler.md) ^1.2.0
- [jsonwebtoken](https://npm.io/package/jsonwebtoken.md) ^9.0.1
- [memory-pager](https://npm.io/package/memory-pager.md) ^1.5.0
- [range-parser](https://npm.io/package/range-parser.md) ^1.2.1
- [regexpu-core](https://npm.io/package/regexpu-core.md) ^5.3.2
- [safer-buffer](https://npm.io/package/safer-buffer.md) ^2.1.2
- [serve-static](https://npm.io/package/serve-static.md) ^1.15.0
- [side-channel](https://npm.io/package/side-channel.md) ^1.0.4
- [smart-buffer](https://npm.io/package/smart-buffer.md) ^4.2.0
- [toidentifier](https://npm.io/package/toidentifier.md) ^1.0.1
- [array-flatten](https://npm.io/package/array-flatten.md) ^1.1.1
- [color-convert](https://npm.io/package/color-convert.md) ^1.9.3
- [function-bind](https://npm.io/package/function-bind.md) ^1.1.1
- [get-intrinsic](https://npm.io/package/get-intrinsic.md) ^1.2.1
- [node-releases](https://npm.io/package/node-releases.md) ^2.0.13
- [balanced-match](https://npm.io/package/balanced-match.md) ^1.0.2
- [core-js-compat](https://npm.io/package/core-js-compat.md) ^3.31.1
- [is-binary-path](https://npm.io/package/is-binary-path.md) ^2.1.0
- [is-core-module](https://npm.io/package/is-core-module.md) ^2.12.1
- [normalize-path](https://npm.io/package/normalize-path.md) ^3.0.0
- [object-inspect](https://npm.io/package/object-inspect.md) ^1.12.3
- [path-to-regexp](https://npm.io/package/path-to-regexp.md) ^0.1.7
- [setprototypeof](https://npm.io/package/setprototypeof.md) ^1.2.0
- [supports-color](https://npm.io/package/supports-color.md) ^5.5.0
- [to-regex-range](https://npm.io/package/to-regex-range.md) ^5.0.1
- [brace-expansion](https://npm.io/package/brace-expansion.md) ^1.1.11
- [lodash.debounce](https://npm.io/package/lodash.debounce.md) ^4.0.8
- [sparse-bitfield](https://npm.io/package/sparse-bitfield.md) ^3.0.3
- [cookie-signature](https://npm.io/package/cookie-signature.md) ^1.0.6
- [path-is-absolute](https://npm.io/package/path-is-absolute.md) ^1.0.1
- [binary-extensions](https://npm.io/package/binary-extensions.md) ^2.2.0
- [merge-descriptors](https://npm.io/package/merge-descriptors.md) ^1.0.1
- [convert-source-map](https://npm.io/package/convert-source-map.md) ^1.9.0
- [to-fast-properties](https://npm.io/package/to-fast-properties.md) ^2.0.0
- [webidl-conversions](https://npm.io/package/webidl-conversions.md) ^7.0.0
- [content-disposition](https://npm.io/package/content-disposition.md) ^0.5.4
- [ecdsa-sig-formatter](https://npm.io/package/ecdsa-sig-formatter.md) ^1.0.11
- [regenerator-runtime](https://npm.io/package/regenerator-runtime.md) ^0.13.11
- [electron-to-chromium](https://npm.io/package/electron-to-chromium.md) ^1.4.473
- [escape-string-regexp](https://npm.io/package/escape-string-regexp.md) ^1.0.5
- [fs-readdir-recursive](https://npm.io/package/fs-readdir-recursive.md) ^1.1.0
- [regenerator-transform](https://npm.io/package/regenerator-transform.md) ^0.15.1
- [update-browserslist-db](https://npm.io/package/update-browserslist-db.md) ^1.0.11
- [buffer-equal-constant-time](https://npm.io/package/buffer-equal-constant-time.md) ^1.0.1
- [babel-plugin-polyfill-corejs2](https://npm.io/package/babel-plugin-polyfill-corejs2.md) ^0.4.5
- [babel-plugin-polyfill-corejs3](https://npm.io/package/babel-plugin-polyfill-corejs3.md) ^0.8.3
- [mongodb-connection-string-url](https://npm.io/package/mongodb-connection-string-url.md) ^2.6.0
- [regenerate-unicode-properties](https://npm.io/package/regenerate-unicode-properties.md) ^10.1.0
- [supports-preserve-symlinks-flag](https://npm.io/package/supports-preserve-symlinks-flag.md) ^1.0.0
- [babel-plugin-polyfill-regenerator](https://npm.io/package/babel-plugin-polyfill-regenerator.md) ^0.5.2
- [unicode-match-property-ecmascript](https://npm.io/package/unicode-match-property-ecmascript.md) ^2.0.0
- [unicode-property-aliases-ecmascript](https://npm.io/package/unicode-property-aliases-ecmascript.md) ^2.1.0
- [unicode-match-property-value-ecmascript](https://npm.io/package/unicode-match-property-value-ecmascript.md) ^2.1.0
- [unicode-canonical-property-names-ecmascript](https://npm.io/package/unicode-canonical-property-names-ecmascript.md) ^2.0.0

## Alternatives

- [@pothos/plugin-authz](https://npm.io/package/@pothos/plugin-authz.md) — 12.4K weekly downloads
- [@bounded-sh/client](https://npm.io/package/@bounded-sh/client.md) — 3.2K weekly downloads
- [@luigi-project/plugin-auth-oauth2](https://npm.io/package/@luigi-project/plugin-auth-oauth2.md) — 2.3K weekly downloads
- [@nocobase/plugin-verification](https://npm.io/package/@nocobase/plugin-verification.md) — 2.0K weekly downloads
- [escher-request](https://npm.io/package/escher-request.md) — 545 weekly downloads

## Recent versions

- 1.1.15 (latest) — 2024-07-07
- 1.1.14 — 2024-07-07
- 1.1.13 — 2024-07-07
- 1.1.12 — 2024-07-07
- 1.1.11 — 2024-07-06
- 1.1.10 — 2024-07-06
- 1.1.9 — 2024-07-06
- 1.1.8 — 2024-07-06
- 1.1.7 — 2024-07-06
- 1.1.6 — 2024-07-06
- 1.1.5 — 2024-07-06
- 1.1.4 — 2024-07-06
- 1.1.3 — 2024-07-06
- 1.1.2 — 2024-07-06
- 1.1.1 — 2023-07-27
- … 2 more at https://npm.io/package/express-jwt-authenticator/versions

## README

# express-jwt-authenticator

express-jwt-authenticator is a powerful and secure Node.js authentication package that simplifies the implementation of JSON Web Token (JWT) based authentication in your applications. It provides a robust and flexible solution for user registration, login, and protected route management, ensuring a seamless and secure user experience.

Provides you Methods for _registration_, _login_, _user account deletion_, _password change_,_email sending method_, _password verification through email_ and a middleware for protecting other routes named _protect_.

## Installation

To integrate `express-jwt-authenticator` into your Node.js project, install it via npm:

```bash
npm install express-jwt-authenticator
```

## Configuration

Before using `express-jwt-authenticator`, make sure to set up the following environment variables in your project in .env file:

```dotenv
JWT_SECRET=your_jwt_secret                           # Secret key used to sign JWT tokens
JWT_EXPIRES_IN=7d                                    # Expiry time for JWT tokens (e.g., "1d", "2h")
EMAIL_USER=your_email@example.com                    # Email address for sending verification emails
EMAIL_PASS=your_email_password_or_app_password       # Password or app-specific password for the above email
HOST=http://localhost:8000                           # Base URL for your application
EMAIL_VERIFICATION_ROUTE=verify-email               # Route for email verification link
LOGIN_URL=https://www.instagram.com/                #Login page link of your application
CONNECTION_STRING=`your database connection string` #connection url for mongodb
```

## Sample Usage

### 1. Make sure, your express application is running and is successfully connected to the database

### 2. Use the Authentication Methods in Your Express App/Sample Usage

Integrate the provided authentication functions into your Express application by setting up routes as shown below:

```js
const express = require("express");
const app = express();

app.use(express.json()); // Middleware to parse JSON bodies
const {
  initiateRegistration,
  completeRegistration,
  login,
  protect,
  deleteUserAccount,
  changePassword,
} = require("express-jwt-authenticator");

// Adding Config File Contents to process
require("dotenv").config({ path: "./config.env" });

const PORT = process.env.PORT || 8000;
const CONNECTION_STRING = process.env.CONNECTION_STRING;

const connectDb = require("./db.js");

// Load environment variables from .env file
require("dotenv").config();

// Database Connection
connectDb(CONNECTION_STRING);

// Route to initiate user registration
app.post("/initiateRegistration", initiateRegistration);

// Route to complete registration (typically through email verification)
app.get(
  `/${process.env.EMAIL_VERIFICATION_ROUTE}/:token`,
  completeRegistration
);

// Route to login and obtain a JWT token
app.post("/login", login);

// Route to change the user's password (protected)
app.post("/change-password", protect, changePassword);

// Route to delete the authenticated user's account (protected)
app.delete("/delete", protect, deleteUserAccount);

// Example of a protected route that only authenticated users can access
app.get("/myroute", protect, (req, res) => {
  res.send("Protected route, only authenticated users can access this.");
});

app.listen(PORT, () => {
  console.log(`Application listening on port ${PORT}`);
});
```

### 3. Connectdb function for database connection

```js
const mongoose = require("mongoose");

const connectDb = (CONNECTION_STRING) => {
  mongoose
    .connect(CONNECTION_STRING)
    .then((conn) => {
      console.log(
        `Database connection successful on link : ${CONNECTION_STRING}`
      );
    })
    .catch((err) => {
      console.log("There was a problem while connecting to the database", err);
    });
};

module.exports = connectDb;
```

## Documentation for Functions

### `initiateRegistration`

- **Description:** Initiates the user registration process by generating a verification email.
- **Method:** `POST`
- **Route:** `/initiateRegistration`
- **Request Body:**
  - `email` (string, required): The email address of the user.
  - `password` (string, required): The password for the user account.
- **Response:**
  - **Success:**
    - `status`: `"success"`
    - `message`: `"Verification email sent successfully. Please check your email."`
  - **Failure:**
    - `status`: `"fail"`
    - `message`: Detailed error message explaining the failure.

**Example Request:**

```json
{
  "email": "user@example.com",
  "password": "securePassword123"
}
```

### `completeRegistration`

This route would be hit by the user through the link sent to him on his/her email for verification.

- **Description:** Completes the registration process by verifying the email and creating the user.
- **Method:** `POST`
- **Route:** `/completeRegistration`
- **Request Body:**
  - `token` (string, required): The email verification token sent to the user's email.
- **Response:**
  - **Success:**
    - `status`: `"success"`
    - `message`: `"User account created successfully."`
  - **Failure:**
    - `status`: `"fail"`
    - `message`: `"Invalid or expired verification token."`

### `login`

- **Description:** Logs in a user with their email and password to obtain a JWT token.
- **Method:** `POST`
- **Route:** `/login`
- **Request Body:**
  - `email` (string, required): The email address of the user.
  - `password` (string, required): The password for the user account.
- **Response:**
  - **Success:**
    - `token` (string): JWT token for authenticated access.
    - `status`: `"success"`
  - **Failure:**
    - `status`: `"fail"`
    - `error`: Detailed error message explaining the failure.

**Example Request:**

```json
{
  "email": "user@example.com",
  "password": "securePassword123"
}
```

### `changePassword`

- **Description:** Changes the password for the authenticated user.
- **Method:** `POST`
- **Route:** `/changePassword`
- **Request Body:**
  - `oldPassword` (string, required): The current password of the user.
  - `newPassword` (string, required): The new password to be set for the user account.
- **Response:**
  - **Success:**
    - `status`: `"success"`
    - `message`: `"Password updated successfully."`
  - **Failure:**
    - `status`: `"fail"`
    - `message`: Detailed error message explaining the failure.

**Example Request:**

```json
{
  "oldPassword": "currentPassword123",
  "newPassword": "newSecurePassword456"
}
```

### `deleteUserAccount`

- **Description:** Deletes the account of the authenticated user.
- **Method:** `DELETE`
- **Route:** `/deleteUserAccount`
- **Request Headers:**
  - `Authorization` (string, required): JWT token in the format `"Bearer <token>"` for authentication.
- **Response:**
  - **Success:**
    - `status`: `"success"`
    - `message`: `"User account deleted successfully."`
  - **Failure:**
    - `status`: `"fail"`
    - `message`: Detailed error message explaining the failure.

**Example Request:**

```http
DELETE /deleteUserAccount
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

### Adding `protect` Middleware

To secure routes that require authentication, use the `protect` middleware before defining your route handlers. This ensures that only authenticated users can access protected routes.

**Example Usage:**

```js
const express = require("express");
const app = express();
const {
  protect,
  login,
  deleteUserAccount,
} = require("express-jwt-authenticator");

// Example: Protecting a route that requires authentication
app.get("/protectedRoute", protect, (req, res) => {
  res.json({ message: "This is a protected route!" });
});

// Example: Using protect with other functions
app.post("/login", login);
app.delete("/deleteUserAccount", protect, deleteUserAccount);

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
```

### `sendMail`

- **Description:** Sends an email using the Gmail SMTP service. Useful for sending verification emails, notifications, and other communications.
- **Function Call:** `sendMail(from, to, subject, text,from,password/app password, html)`
- **Parameters:**
  - `from` (string, required): The email address of the sender.
  - `to` (string, required): The email address of the recipient.
  - `subject` (string, required): The subject line of the email.
  - `text` (string, required): The plain text version of the email content.
  - `from` (string, required): The email address of the sender.
  - `app password/password` (string,required): The password or the app password of the email.
  - `html` (string, optional): The HTML version of the email content.
- **Returns:** A Promise that resolves when the email is successfully sent.

**Example Usage:**

```js
const { sendMail } = require("express-jwt-authenticator");

// Example function to send an email through a protected route
  app.get("/myroute", protect, async (req, res) => {
    try {
      await sendMail(
        process.env.EMAIL_USER, // from
        "userEmail@gmail.com", // to
        "Welcome to our application", // subject
        `Hello user, We appreciate your interest in our application, and that's really nice of you. Thankyou!`, // text
        process.env.EMAIL_USER, //from
        process.env.EMAIL_PASS  //app password, email password
      );
      console.log("email sent successfully.");
    } catch (error) {
      console.error("Error sending email:", error);
    }
    return res.send(
      "Protected route, only authenticated users can access this."
    );
  });
};

```

---
_Source: https://npm.io/package/express-jwt-authenticator · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
