r/webdev • u/Massive_Dish_3255 • Oct 27 '26
Question How should I integrate an existing NestJS authentication system with a React + Flowbite React frontend?
I'm developing a Grievance Redressal Portal as a learning project. My backend is built with NestJS, TypeScript, Prisma, and PostgreSQL.
I have been implementing authentication (User Sign In and Sign Out) using the "@nestjs/authentication" package of NestJS v12.
I would like to know conceptually the changes to be made to my back end such that I should be able to extend the authentication feature to a React-based front-end.
I have adapted the code by hand from the "Register The Authentication Module" and "Add Sign-Up and Sign-In" sections of the NestJS docs for NestJS v12: Authentication | NestJS - A progressive Node.js framework
I am posting my code here.
//sign-in.dto.ts
import { PickType } from "@nestjs/swagger";
import { UserUniversalDto } from "../../users/dto/user-universal.dto";
export class SignInDto extends PickType (
UserUniversalDto,
['user_email', 'user_password']
) {};
//credentials.service.ts
import { ConflictException, Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service.js';
import { CreateUserDto } from '../users/dto/create-user.dto.js';
import { FindUserByEmailDto } from '../users/dto/find-user-by-email.dto.js';
import * as argon2 from 'argon2';
import { USER_STATUS } from '../users/user.constants.js';
()
export class CredentialsService {
constructor(
private readonly usersService: UsersService
) {}
async register(createUserDto: CreateUserDto) {
const findUserByEmailDto: FindUserByEmailDto = {
user_email: createUserDto.user_email
}
// Don't create the user if the email already exists.
if (await this.usersService.findUserByEmail(findUserByEmailDto)) {
throw new ConflictException('Email already registered. User already exists.');
}
// The address is unverified: anyone can type any email into a sign-up form.
const registered_user = await this.usersService.createUser(createUserDto);
return registered_user;
}
/** The user, or null when the email or the password is wrong. */
async verify(email: string, password: string) {
const findUserByEmailDto: FindUserByEmailDto = {
user_email: email
}
const found_user = await this.usersService.findUserByEmail(findUserByEmailDto);
// Checking if the user exists.
if (!found_user) {
throw new ConflictException('User does not exist. Login rejected.');
}
// If the user is suspended, reject login by throwing an exception.
if (found_user.user_status === USER_STATUS.SUSPENDED) {
throw new ConflictException('User is suspended. Login rejected. Please contact admin.');
}
// If the found_user's password is wrong, (password_hash doesn't match) then the it should return null.
const password_hash: string | null | undefined = found_user?.user_password;
const password_check = await argon2.verify(password_hash as string, password);
// Checking if the user's password is correct.
if (password_check !== true) {
throw new ConflictException('Incorrect username or password. Login rejected.');
}
return found_user;
}
}
//myauthentication.controller.ts
import { Body, Controller, HttpCode, Post, UnauthorizedException } from '@nestjs/common';
import { Public, SignInService } from '@nestjs/authentication';
import { SignInDto } from './dto/sign-in.dto';
import { CredentialsService } from './credentials.service';
import { CreateUserDto } from '../users/dto/create-user.dto';
()
('auth')
export class MyAuthenticationController {
constructor(
private readonly credentialsService: CredentialsService,
private readonly signInService: SignInService,
) {}
('sign-up')
async signUp(@Body() createUserDto: CreateUserDto) {
const user = await this.credentialsService.register(createUserDto);
var string_user_id = String(user.user_id);
await this.signInService.signIn(string_user_id, { method: 'password' });
return user;
}
('sign-in')
(200)
async signIn(@Body() signInDto: SignInDto) {
const user = await this.credentialsService.verify(signInDto.user_email, signInDto.user_password);
var string_user_id = String(user.user_id);
const { session } = await this.signInService.signIn(string_user_id, { method: 'password' });
return { mfaRequired: session.mfa === 'pending' };
}
('sign-out')
(204)
async signOut() {
if (!(await this.signInService.signOut())) {
throw new UnauthorizedException();
}
}
}
//myauthentication.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module';
import { SessionAuth } from './session-auth.provider';
import { MyAuthenticationController } from './myauthentication.controller';
import { CredentialsService } from './credentials.service';
({
imports: [UsersModule],
controllers: [MyAuthenticationController],
providers: [SessionAuth,
CredentialsService
]
})
export class MyAuthenticationModule {}
//session-auth.provider.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, SessionCookieProvider, type SessionRecord } from '@nestjs/authentication';
import { UsersService } from '../users/users.service.js';
import type { User as PrismaUser } from '../generated/prisma/client.js';
export type User = Omit<PrismaUser, 'user_password'>;
()
export class SessionAuth extends SessionCookieProvider<User> {
constructor(
private readonly usersService: UsersService,
registry: AuthenticationRegistry,
) {
super();
// Adds this provider to the chain the guard runs for every request.
registry.registerProvider(this);
}
// Called for every request with a live session cookie.
// Returning null (the user was deleted) ends the session.
validate(session: SessionRecord) {
console.log("In validate() in SessionAuth")
const user_id = session.userId;
var numeric_user_id = Number(user_id);
return this.usersService.findOneUser(numeric_user_id);
}
}
NOTE 1: The authentication system uses server-side sessions managed through nestjs/authentication and a session cookie. The package's SessionCookieProvider reads the cookie and loads the user through the validate() method.
NOTE 2: I am also asking this question since NestJS v12 has only been released on August 27, 2026 and there don't seem to be many resources that show how to extend this system to the front-end.
1
u/Massive_Dish_3255 Oct 28 '26
Thank you everyone.
3
u/Existing-Scar9191 Oct 27 '26
On the backend, the main changes are enabling CORS for your React dev origin and deciding how the session is carried. For a learning project I'd go with an httpOnly cookie (credentials: true in CORS, plus credentials: 'include' on the frontend fetch or axios calls), so you're not storing tokens in localStorage. Also add a small /auth/me endpoint that returns the current user. On the React side, call /auth/me on app load and put the result in a context. Then protected routes just check whether that user exists. Treat a 401 from any request as 'logged out' and redirect to sign-in.
2
u/AbdelrhmanDev Oct 27 '26
the cookie answer above is the right direction, and on the react side the piece that saves you pain is one central fetch wrapper with credentials included so every request carries the cookie, and a 401 handler in that same wrapper that bounces the user back to the login page instead of failing silently in random components. one more thing once cookies are involved cross-origin, look at csrf protection early, even a simple token endpoint pattern, because its the thing everyone defers and then has to retrofit
2
u/Boring_Occasion_3526 Oct 27 '26
Keep it simple, have NestJS issue HTTP-only cookies and let the React app just call a /me endpoint on load , … trying to juggle tokens in localStorage always turns into a refresh-token headache later. The frontend doesn't need to know how auth works, just whether the user is in.
1
u/NoClipCheck Oct 27 '26
Everyone's covered the session side well, so one thing on authorization, since a grievance portal will have regular users and staff. Being signed in isn't the same as being allowed. For every route that takes an id, like
GET /grievances/:id, check on the server that the grievance belongs toreq.useror that the user has a staff role. Otherwise anyone logged in can change the number and read other people's complaints. Put role checks in a guard (@Roles('admin')plus aRolesGuard) instead of just hiding buttons in React, since anyone can call the API with a plain fetch. Also scope Prisma queries withwhere: { id, userId }rather than fetching by id and checking afterwards.1
u/No-Molasses-2097 Oct 27 '26
Flowbite does not really change the auth part here, so I would treat it as just the form and layout. The part I would watch is sign out. Make sure it calls the backend to end the session, so the cookie does not still work after the user thinks they logged out. A quick check is signing out and then trying to load a protected page again.
1
u/mithuretnam Nov 04 '26
Since you're already on session cookies, mostly keep that. Serve React from the same site (or proxy /api in dev) so the cookie is first-party, set it httpOnly, Secure, SameSite=Lax, enable CORS with credentials: true and an explicit origin, and use fetch with credentials: 'include'. Add a /me endpoint React calls on load, plus CSRF protection on state-changing routes. No need to switch to JWTs in localStorage.