JWT Middleware
Let's create the middleware to handle the authentications. Create this file src/middlewares/jwt.middleware.ts
.
This middleware takes the Authorization
header (Bearer [token]) and get the token. jsonwebtoken
packages handles the process of validating the token behind the scene.
If the token doesn't exist, the access is denied (401 Error). Else, we validated the token, the package handles the token and return an error if it's expired or invalid (in case not expired, then it's invalid). Otherwise, it's valid, and we move on to the next handler (The route handler probably).
The IRequest
interface is a globally declared interface, it extends default Express Request, and add user payload (userId
). We can use this userId
in other route handler to get the logged in user. Create src/index.d.ts
Auth Router
Router
As I mentioned in the Architecture section, the code will be separated, the router will only handle routing and listening. The logic will be in repositories files. Let's create the file src/routes/v1/auth.route.ts
This router depends on 3 other files; The types and ZOD schema, the ZOD validator middleware, and the Auth Repo.
ZOD Validator Middleware.
All middlewares are injected in src/middlewares
directory. So, let's create the middleware. Create validateRequest.middleware.ts
file.
This middleware is simple. ZOD validates the schema passed through the middleware in Router handler. If it's valid, move to next handler. Otherwise, return a 422 response with the ZOD error to know which property isn't valid and what's the error. That's the role of parseZodErrors
. It parses the ZodErrors
to the ApiResponseBody
message property.
ZOD Schemas
I used a class with static ZOD schema object to have a clean import section. And used .d.ts
to declare the types. So, we got two files; the schema objects file, and type definitions file. Create a file src/schemas/auth/auth.schema.ts
Now create the definition file src/schemas/auth/auth.schema.d.ts
This definition is already declared in index.d.ts
. We won't need to import each type in each file we use.
Setting up prisma
Before we start with the repository, we need to create the prisma models and migrate them. Create the schema in prisma/schema.prisma
Now we migrate our schema. Make sure you created the DB and added the URL in .env
And because we will handle also the TEST DB, I created a script to migrate the migrations in that DB. Create the file in prisma/scripts/migrate.ts
.
Install cross-env
before, and make sure you installed ts-node
like mentioned before.
After that, you can run the script