Cookies
- An HTTP cookie is a small piece of data stored by the user's browser.
- Cookies were designed to be a reliable mechanism for websites to remember stateful information. When the user visits the website again, the cookie is automatically sent with the request.
Install cookie parser
npm i cookie-parser
npm i -D @types/cookie-parser
Cookies Configuration
import * as cookieParser from 'cookie-parser';
const app = await NestFactory.create(AppModule);
app.use(cookieParser());
Request Cookies
@Get()
findAll(@Req() request: Request) {
console.log(request.cookies);
}
Response Cookies
@Get()
findAll(@Res({ passthrough: true }) response: Response) {
response.cookie('key', 'value');
}
Cookie based token validation
@Injectable()
export class AuthMiddleware implements NestMiddleware {
async use(req: Request, res: Response, next: NextFunction) {
const cookies = req.cookies;
const token = cookies.token;
console.log("Token:", token);
if (!token) {
throw new UnauthorizedException(
{ status: HttpStatus.UNAUTHORIZED, message:'Unauthorized'}
);
}
next();
}
}