65-Nodejs Course 2023: Auth: Decoupling JWT
Tags: node, typescript, mongodb, fastify
Published: 2022-11-16 10:52:31

---
title: 65-Nodejs Course 2023: Auth: Decoupling JWT
published: true
description: 
series: Nodejs Course 2023
tags: nodejs, typescript, mongodb, fastify
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8qdbdgyfwaas285nf14l.png
# Use a ratio of 100:42 for best results.
---

In our previous article, we'have made our first successful login, now let's decouple the JWT handler.

## Decoupling JWT

Why would we do that? well, because of two main reasons, the first one is to make it accessible from everywhere in the application not in the http folder only and secondly if we wanted to change the JWT handler later, we can easily do it when it is decoupled.

Let's create a new folder called `jwt` in `src/core/auth` and create a new file called `jwt.ts` in it, then let's move the JWT handler from `src/core/auth/registerAuthRoutes.ts` to `src/core/jwt/jwt.ts`.

```ts
// src/core/auth/jwt.ts
import request from "core/http/request";
import { getServer } from "core/http/server";

const jwt = {
  /**
   * Generate a new JWT token for the user
   */
  async generate(payload: any, options?: any) {
    return getServer().jwt.sign(payload, options);
  },
  /**
   * Verify Current token from request which will be in the `Authorization` header
   */
  async verify() {
    return await request.baseRequest.jwtVerify();
  },
};

export default jwt;
```

So basically what we did here is we created an object with tw methods, one to generate a new JWT token and the other to verify it, then we exported it, both methods are `async` because we are using `await` in the `verify` method.

Now let's import the JWT handler in `src/core/auth/registerAuthRoutes.ts` and use it instead of the old one.

```ts
// src/core/auth/registerAuthRoutes.ts
import { Response } from "core/http/response";
import { getServer } from "core/http/server";
import router from "core/router";
import jwt from "./jwt";
import AccessToken from "./models/access-token";

export default function registerAuthRoutes() {
  // get server instance
  const server = getServer();

  // now let's add a guests route in our routes to generate a guest token to our guests.
  router.post("/guests", (_request, response: Response) => {
    // use our own jwt generator to generate a token for the guest
    const token = jwt.generate({ userType: "guest" });

    AccessToken.create({
      token,
      userType: "guest",
    });

    return response.send({
      accessToken: token,
      userType: "guest",
    });
  });

  // now let's add an event to validate the request token
  server.addHook("onRequest", async (request, reply) => {
    if (request.url === "/guests") return;

    try {
      // use our own jwt verify to verify the token
      await jwt.verify();
    } catch (err) {
      reply.status(401).send({
        error: "Unauthorized: Invalid Access Token",
      });
    }
  });
}
```

Now what remains is that we need to create the current `user` function which returns the current user model, which can be an instance of `Guest` model or `User` model and so on.

This is what we're going to do in our next chapter.

## 🎨 Conclusion

In this chapter, we've decoupled the JWT handler, so we can use it from everywhere in the application.

## 🚀 Project Repository

You can find the latest updates of this project on [Github](https://github.com/hassanzohdy/nodejs-2023)

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) to get help and support (Node Js 2023 Channel).

## 🎞️ Video Course (Arabic Voice)

If you want to learn this course in video format, you can find it on [Youtube](https://www.youtube.com/playlist?list=PLGO8ntvxgiZMJc7RN2lIq9WmMOlWZGzmz), the course is in Arabic language.

## 📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [OOP In JS And TS From The Very Beginning](https://dev.to/hassanzohdy/jsts-oop-course-1-introduction-2ld)
* [ES6++: The Ultimate Guide to ES6 and Beyond](https://dev.to/hassanzohdy/es6-1-introduction-h3e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)