Introduction
This article provides a comprehensive, step-by-step guide to implementing authentication and authorization in a NestJS backend application with Clerk.
What is Clerk?
Clerk is a comprehensive platform offering embeddable user interfaces, flexible APIs, and an intuitive and robust dashboard for seamless user authentication and management. It covers everything from session management and multi-factor authentication to social sign-ons, magic links, email or SMS one-time passcodes and more.
Why use Clerk?
Authentication and security requirements, trends, and best practices are always evolving because data protection and privacy are increasingly important. By offloading these responsibilities to a specialized service provider, you can focus on building the core features of your application and ship faster.
Platforms like Clerk exist to take on these security tasks for you.
Prerequisites
- Basic knowledge of Typescript
- Familiarity with NestJS Fundamentals
- Understanding of authentication concept on the backend
- Running Node 18 or latest
Project setup
This project requires a new or existing NestJS project, a Clerk account and application, and libraries like Passport, Passport Strategy and Clerk backend SDK.
Creating a NestJS project
You can easily set up a new NestJS project using the Nest CLI. With any package manager you prefer, run the following commands to create a new Nest application:
$ pnpm add -g @nestjs/cli $ nest new clerk-auth
Checkout the NestJS documentation for more details.
Setting up your Clerk account and application
If you don’t already have one, create a Clerk account and set up a new application in the Clerk dashboard. You can get started on Clerk website.
Installing required libraries
The required libraries for this project can be installed with this command:
$ pnpm add @clerk/backend @nestjs/config @nestjs/passport passport passport-custom
Environment configuration
Create a .env file in the root directory of your project to manage variables for different environments, production, development or staging.
Add the following variables, replacing the placeholders with the actual keys obtained from your Clerk account dashboard.
# .env CLERK_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEY CLERK_SECRET_KEY=YOUR_SECRET_KEY
To access environment variables throughout the application using the ConfigService, import the ConfigModule into the root AppModule.
// src/app.module.ts import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, }), ], }) export class AppModule {}
Integrating Clerk in NestJS
This section explains how to integrate and utilize the Clerk backend SDK in your NestJS project.
Creating a Clerk client provider
Registering the Clerk client as a provider makes it injectable into classes using a decorator, allowing it to be used wherever needed throughout the codebase, as demonstrated in the upcoming sections.
$ pnpm add -g @nestjs/cli $ nest new clerk-auth
Registering the ClerkClientProvider in AppModule
Next, you need to register the provider with Nest to enable dependency injection.
$ pnpm add @clerk/backend @nestjs/config @nestjs/passport passport passport-custom
Using Passport with Clerk-Issued JWT
Clerk issues a JWT token when a user signs up or logs in through Clerk’s hosted pages or a frontend app. This token is then sent as a bearer token in the Authorization header of requests made to the NestJS backend application.
Creating a Clerk Strategy
In NestJS, Passport is the recommended way to implement authentication strategies. You’ll create a custom Clerk strategy that verifies tokens with Clerk client.
# .env CLERK_PUBLISHABLE_KEY=YOUR_PUBLISHABLE_KEY CLERK_SECRET_KEY=YOUR_SECRET_KEY
The validate() method returns user data that NestJS automatically attaches to the request.user.
Creating an Auth Module
Create an AuthModule that provides the Clerk strategy and integrates with the PassportModule. Then, register the AuthModule in the AppModule.
// src/app.module.ts import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, }), ], }) export class AppModule {}
// src/providers/clerk-client.provider.ts import { createClerkClient } from '@clerk/backend'; import { ConfigService } from '@nestjs/config'; export const ClerkClientProvider = { provide: 'ClerkClient', useFactory: (configService: ConfigService) => { return createClerkClient({ publishableKey: configService.get('CLERK_PUBLISHABLE_KEY'), secretKey: configService.get('CLERK_SECRET_KEY'), }); }, inject: [ConfigService], };
Implementing routes protections
Protected routes are routes that require the user to be authenticated before they can access them.
Creating Clerk authentication guard
Guards determine whether a specific request should be processed by a route handler based on certain runtime conditions.
If you want to protect all routes in your application by default, you’ll need to take the following steps:
- Create a Public decorator to mark routes that should be accessible without authentication.
- Implement a ClerkAuthGuard to restrict access to protected routes, allowing only authenticated users to proceed.
// src/app.module.ts import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { ClerkClientProvider } from 'src/providers/clerk-client.provider'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, }), ], providers: [ClerkClientProvider], }) export class AppModule {}
// src/auth/clerk.strategy.ts import { User, verifyToken } from '@clerk/backend'; import { Injectable, Injectable, UnauthorizedException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-custom'; import { UsersService } from 'src/users/users.service'; import { Request } from 'express'; import { ClerkClient } from '@clerk/backend'; @Injectable() export class ClerkStrategy extends PassportStrategy(Strategy, 'clerk') { constructor( @Inject('ClerkClient') private readonly clerkClient: ClerkClient, private readonly configService: ConfigService, ) { super(); } async validate(req: Request): Promise<user> { const token = req.headers.authorization?.split(' ').pop(); if (!token) { throw new UnauthorizedException('No token provided'); } try { const tokenPayload = await verifyToken(token, { secretKey: this.configService.get('CLERK_SECRET_KEY'), }); const user = await this.clerkClient.users.getUser(tokenPayload.sub); return user; } catch (error) { console.error(error); throw new UnauthorizedException('Invalid token'); } } } </user>
Enabling authentication globally
Since most of your endpoints will be protected by default, you can configure the authentication guard as a global guard.
// src/auth/auth.module.ts import { Module } from '@nestjs/common'; import { ClerkStrategy } from './clerk.strategy'; import { PassportModule } from '@nestjs/passport'; import { ClerkClientProvider } from 'src/providers/clerk-client.provider'; import { ConfigModule } from '@nestjs/config'; @Module({ imports: [PassportModule, ConfigModule], providers: [ClerkStrategy, ClerkClientProvider], exports: [PassportModule], }) export class AuthModule {}
Defining Protected and Public Routes
In these two controllers, the Public decorator is used in the AppController to designate a route as public. In contrast, no decorator is needed in the AuthController to specify routes as protected, as the authentication guard is applied globally by default.
// src/app.module.ts import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { ClerkClientProvider } from 'src/providers/clerk-client.provider'; import { AuthModule } from 'src/auth/auth.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, }), AuthModule, ], providers: [ClerkClientProvider], }) export class AppModule {}
// src/decorators/public.decorator.ts import { SetMetadata } from '@nestjs/common'; export const IS_PUBLIC_KEY = 'isPublic'; export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
Note: Remember to register the AppController in the AppModule and the AuthController in the AuthModule.
Conclusion
Clerk as a platform handles authentication and security responsibilities, keeping up with the latest trends and best practices. This enables you to focus on building your application’s core features and accelerating your development process.
In this guide, we’ve covered the steps to implement Clerk authentication, from setting up the project to securing routes. These foundational steps should help you get started on your journey of exploring the possibilities with an authentication service platform.
A fully functional example of this project is included at the end of this article.
thedammyking
/
clerk-nest-auth
Using Clerk authentication and user management in NestJS backend application
Clerk-NestJS Authentication
Using Clerk authentication and user management in NestJS backend application
What's inside?
This monorepo includes the following packages and apps:
Apps and Packages
- api: a NestJS app
Each package and app is 100% TypeScript.
Utilities
This monorepo has some additional tools already setup for you:
- TypeScript for static type checking
- ESLint for code linting
- Prettier for code formatting
The above is the detailed content of Authentication with Clerk in NestJS Server Application. For more information, please follow other related articles on the PHP Chinese website!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
