Skip to content

Commit

Permalink
feat: add cors with whitelist and validate config
Browse files Browse the repository at this point in the history
  • Loading branch information
JDIZM committed Jan 11, 2024
1 parent 9e07e8a commit bfc5a31
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 3 deletions.
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ NODE_ENV=development
POSTGRES_HOST=localhost
POSTGRES_USER=postgres
POSTGRES_PASSWORD=example
POSTGRES_DB=test
POSTGRES_DB=test

APP_URL=http://localhost:3000
41 changes: 41 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"license": "ISC",
"devDependencies": {
"@prisma/client": "^5.2.0",
"@types/cors": "^2.8.17",
"@types/node": "^20.2.1",
"@types/pg": "^8.10.9",
"@typescript-eslint/eslint-plugin": "^5.57.0",
Expand Down Expand Up @@ -66,6 +67,7 @@
"@types/bcrypt": "^5.0.0",
"@types/express": "^4.17.17",
"bcrypt": "^5.1.1",
"cors": "^2.8.5",
"drizzle-orm": "^0.29.3",
"drizzle-zod": "^0.5.1",
"express": "^4.18.2",
Expand Down
3 changes: 2 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ export const config = {
db_host: process.env.POSTGRES_HOST || "localhost",
db_user: process.env.POSTGRES_USER || "postgres",
db_password: process.env.POSTGRES_PASSWORD || "postgres",
db_name: process.env.POSTGRES_DB || "test"
db_name: process.env.POSTGRES_DB || "test",
appUrl: process.env.APP_URL || "http://localhost:3000"
};
27 changes: 26 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@ import express from "express";
import { config } from "./config.js";
import { pinoHttp } from "pino-http";
import { routes } from "./routes/index.js";

import cors from "cors";
const { logger } = pinoHttp();

console.log("config", config);

const checkConfigIsValid = () => {
Object.values(config).forEach((value) => {
if (!value) {
throw new Error("config is invalid");
}
});
};

checkConfigIsValid();

const app = express();

app.use(
Expand All @@ -15,6 +25,21 @@ app.use(
})
);

// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

// parse application/json
app.use(express.json());

const corsWhitelist = [`http://localhost:${config.port}`, config.appUrl];

const corsOptions = {
origin: corsWhitelist,
optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

routes(app);

app.listen(config.port, () => {
Expand Down

0 comments on commit bfc5a31

Please sign in to comment.