익스프레스 경화 치트시트

X-Powered-By




npm install express



import express from "express"

const server = express()

server.disable("x-powered-by")

server.get("/hello", (request, response) => {
  response.send("hello")
})

server.listen(8000, () => {
  console.log("Server is listening")
})


  • Express Production Tips

  • 크로스 오리진 자원 공유




    npm install express cors
    



    import express from "express"
    import cors from "cors"
    
    const server = express()
    
    const allowedOrigins = [
      "yourdomain.com",
      "anotherdomain.com"
    ]
    
    server.use(cors({
      origin: (origin, next) => {
        if (allowedOrigins.includes(origin)) {
          next(null, true)
        } else {
          next(new Error(`${origin} not allowed`))
        }
      }
    }))
    
    server.get("/hello", (request, response) => {
      response.send("hello")
    })
    
    server.listen(8000, () => {
      console.log("Server is listening")
    })
    


  • Cross Origin Resource Sharing
  • cors

  • 보안 헤더




    npm install express helmet
    



    import express from "express"
    import helmet from "helmet"
    
    const server = express()
    
    server.use(helmet())
    
    server.get("/hello", (request, response) => {
      response.send("hello")
    })
    
    server.listen(8000, () => {
      console.log("Server is listening")
    })
    


  • Security Headers
  • helmet

  • 비밀




    npm install express dotenv
    



    import express from "express"
    import dotenv from "dotenv"
    
    dotenv.config()
    
    const connect = (databaseCredentials) => {
      console.log(databaseCredentials)
      // TODO: connect to database
    }
    
    const server = express()
    
    server.get("/hello", (request, response) => {
      const connection = connect(process.env.DATABASE_CREDENTIALS)
    
      response.send("hello")
    })
    
    server.listen(8000, () => {
      console.log("Server is listening")
    })
    


  • dotenv

  • 보안 세션




    npm install express express-session
    



    import express from "express"
    import session from "express-session"
    
    const server = express()
    
    app.use(session({
      secret: process.env.SESSION_SECRET,
      resave: false,
      saveUninitialized: true,
      cookie: {
        secure: true,
        httpOnly: true,
        sameSite: true
      }
    }))
    
    server.get("/hello", (request, response) => {
      response.send("hello")
    })
    
    server.listen(8000, () => {
      console.log("Server is listening")
    })
    


  • Cookie Mozilla Developpers
  • express-session

  • 교차 사이트 요청 위조 보호




    npm install express csurf express-session
    



    import express from "express"
    import csurf from "csurf"
    import session from "express-session"
    
    const server = express()
    
    server.use(session({
      secret: process.env.SESSION_SECRET,
      name: "session",
      resave: false,
      saveUninitialized: true,
      cookie: {
        secure: true,
        httpOnly: true,
        sameSite: true
      }
    }))
    
    const csrfMiddleware = csurf({
      sessionKey: "session"
    })
    
    server.get("/form", csrfMiddleware, (request, response) => {
      response.set("Content-Type", "text/html").send(`
        <!DOCTYPE html>
        <form>
          <input type="email">
        </form>
      `)
    })
    
    server.get("/api/form", csrfMiddleware, (request, response) => {
      response.json({
        _csrf: request.csrfToken()
      })
    })
    
    server.listen(8000, () => {
      console.log("Server is listening")
    })
    


  • Cross Site Request Forgery
  • express-session
  • csrf

  • 매개변수 오염




    npm install express body-parser hpp
    



    import express from "express"
    import bodyParser from "body-parser"
    import hpp from "hpp"
    
    const server = express()
    
    server.use(bodyParser.urlencoded({
      extended: true
    }))
    
    server.use(hpp())
    
    server.get("/hello", (request, response) => {
      response.json({
        name: request.query?.name ?? "unknown"
      })
    })
    
    server.listen(8000, () => {
      console.log("Server is listening")
    })
    


  • Parameters pollution
  • hpp
  • body-parser

  • 신체 검증




    npm install express zod
    



    import express from "express"
    import bodyParser from "body-parser"
    import z from "zod"
    
    const server = express()
    
    server.use(bodyParser.json())
    
    server.post("/api/users", (request, response) => {
      try {
        const schema = z.object({
          email: z.string(),
          password: z.string(),
          confirmation: z.string()
        })
    
        const input = schema.parse(request.body)
    
        response.status(200).send("TODO: save the user")
      } catch (error) {
        response.status(400).send(error.message)
      }
    })
    
    server.listen(8000, () => {
      console.log("Server is listening")
    })
    


  • body-parser
  • zod
  • 좋은 웹페이지 즐겨찾기