Skip to content

Commit a10239f

Browse files
feat: enable configurable trust proxy via TRUST_PROXY environment variable (#202)
1 parent 8b013f7 commit a10239f

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

app/main/src/main.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {AppModule} from "./app.module"
33
import {Logger, LogLevel} from "@nestjs/common"
44
import {CustomLogger} from "./logging/custom-logger"
55
import {Request, Response, NextFunction} from "express"
6+
import {NestExpressApplication} from "@nestjs/platform-express"
67

78
function isDevOrTestEnv(): boolean {
89
return process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test"
@@ -31,7 +32,7 @@ async function bootstrap() {
3132
logLevels
3233
})
3334

34-
const app = await NestFactory.create(AppModule, {logger: logger})
35+
const app = await NestFactory.create<NestExpressApplication>(AppModule, {logger: logger})
3536

3637
if (process.env.ENV === "development") {
3738
Logger.log("Injecting middleware to log OPTIONS requests in development environment.")
@@ -48,6 +49,21 @@ async function bootstrap() {
4849
credentials: true, // Required for the browser to send/receive cookies and 'Authorization' headers.
4950
exposedHeaders: ["Location"]
5051
})
52+
const trustProxy = process.env.TRUST_PROXY
53+
if (trustProxy !== undefined) {
54+
if (trustProxy === "")
55+
throw new Error(
56+
"TRUST_PROXY environment variable cannot be empty. It must be a valid string, number, or boolean."
57+
)
58+
59+
let parsedValue: string | number | boolean = trustProxy
60+
if (trustProxy === "true") parsedValue = true
61+
else if (trustProxy === "false") parsedValue = false
62+
else if (!isNaN(Number(trustProxy))) parsedValue = Number(trustProxy)
63+
64+
app.getHttpAdapter().getInstance().set("trust proxy", parsedValue)
65+
}
66+
5167
app.enableShutdownHooks()
5268
await app.listen(3000)
5369
}

0 commit comments

Comments
 (0)