Skip to content

Commit

Permalink
refactor: move cors to middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Keemluvr committed Jun 14, 2024
1 parent c0bdd0b commit 7b73172
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 16 deletions.
20 changes: 18 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { Module } from '@nestjs/common';
import {
MiddlewareConsumer,
Module,
NestModule,
RequestMethod,
} from '@nestjs/common';

import { ConfigModule } from '@nestjs/config';
import { SequelizeModule } from '@nestjs/sequelize';
Expand All @@ -12,6 +17,7 @@ import { UserModule } from './modules/user/user.module';
import { UserController } from './modules/user/user.controller';
import { AuthService } from './modules/auth/auth.service';
import { AuthModule } from './modules/auth/auth.module';
import { CorsMiddleware } from './core/middleware/cors.middleware';

@Module({
imports: [
Expand All @@ -24,4 +30,14 @@ import { AuthModule } from './modules/auth/auth.module';
controllers: [AppController, UserController],
providers: [AppService, AuthService],
})
export class AppModule {}
export class AppModule implements NestModule {
constructor() {}

configure(consumer: MiddlewareConsumer) {
const middlewares = [CorsMiddleware];

consumer
.apply(...middlewares)
.forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
6 changes: 1 addition & 5 deletions src/core/config/cors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ export default async (app) => {
if (!origin) callback(new Error(errorMessage));

const originIsWhitelisted = allowedOrigins.includes(origin);
const originStartsOrEndsWithAllowed = allowedOrigins.some(
(or) => origin.endsWith(or) || origin.startsWith(or),
);

if (!originIsWhitelisted || !originStartsOrEndsWithAllowed) {
if (!originIsWhitelisted) {
callback(new Error(errorMessage));
}

Expand Down
15 changes: 15 additions & 0 deletions src/core/middleware/cors.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class CorsMiddleware implements NestMiddleware {
constructor() {}

use(request: Request, response: Response, next: () => void) {
const req: any = request;

req.headers.origin = req.headers.origin || req.headers.host;
console.log('>', req.headers);

next();
}
}
9 changes: 0 additions & 9 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,12 @@ import { AppModule } from './app.module';
import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { initSequelizeCLS } from 'sequelize-transactional-decorator';
import { ConfigService } from '@nestjs/config';
import setupCors from './core/config/cors';

initSequelizeCLS();

async function bootstrap() {
const app = await NestFactory.create(AppModule);

app.use(function (req, res, next) {
console.log(req.headers);
req.headers.origin = req.headers.origin || req.headers.host;
next();
});

const configService = app.get(ConfigService);

// ========================================
Expand All @@ -33,8 +26,6 @@ async function bootstrap() {
}),
);

setupCors(app);

await app.listen(configService.get<string>('PORT'));
}
bootstrap();

0 comments on commit 7b73172

Please sign in to comment.