This guide will walk you through the process of creating an authentication service in Node.js using TypeScript and clean architecture. The authentication service will allow users to sign up and log in to your application using email and password.
Before you begin, make sure you have the following:
- Node.js (v14 or higher)
- npm or yarn
- A text editor of your choice (e.g. VS Code)
To set up the project, follow these steps:
-
Create a new directory for your project.
-
Open the directory in your terminal or command prompt.
-
Initialize a new Node.js project using
npm initoryarn init. -
Install the required dependencies:
expressfor building the serverjsonwebtokenfor generating and verifying JSON Web Tokensbcryptfor hashing and verifying passwordsdotenvfor managing environment variablestypeormfor database managementreflect-metadatafor decorators supportpgor any other driver for the desired database engine@types/express,@types/jsonwebtoken,@types/bcrypt,@types/dotenvand@types/pgfor TypeScript support
You can install these dependencies using the following command:
npm install express jsonwebtoken bcrypt dotenv typeorm reflect-metadata pg @types/express @types/jsonwebtoken @types/bcrypt @types/dotenv @types/pg --save
-
Create a
srcdirectory for your source code. -
Inside the
srcdirectory, create aserver.tsfile for your server code.
We will be using the Clean Architecture pattern to structure our code. The Clean Architecture is a software architecture that separates the code into layers with clear boundaries and dependencies pointing inwards. In this architecture, the core business logic is at the center of the architecture, surrounded by layers of less important details. The layers are:
- Entities: Domain models and business rules.
- Use cases: Application-specific business rules.
- Controllers: Handle requests and responses.
- Repositories: Database and external interfaces.
- Services: Manage external services like AWS S3, Twilio, etc.
The following diagram illustrates the Clean Architecture layers:
+----------------+
| Controllers |
+----------------+
| Use Cases |
+----------------+
| Entities |
+----------------+
| Repositories |
+----------------+
| Services |
+----------------+
To set up the Clean Architecture, create the following directories inside the src directory:
domain: Contains theUserentity and any business rules related to authentication.usecases: Contains the use cases for authentication, such asSignupandLogin.interface: Contains the Express.js server code and its associated controllers.