Created
September 29, 2019 10:17
-
-
Save jonathontoon/cce2ad9bf7e446a96882705796e6a131 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SocketManager from "./socketManager"; | |
import http from "http"; | |
import express from "express"; | |
import cors from "cors"; | |
import path from "path"; | |
import SocketIO from "socket.io"; | |
import helmet from "helmet"; | |
import compression from "compression"; | |
import dotenv from "dotenv"; | |
import { RateLimiterMemory } from "rate-limiter-flexible"; | |
dotenv.config(); | |
const app = express(); | |
const server = http.createServer(app); | |
const io = SocketIO(server, { | |
path: "/api", | |
serveClient: false, | |
cookie: false | |
}); | |
const rateLimiter = new RateLimiterMemory({ | |
points: 5, | |
duration: 1, | |
blockDuration: 600 | |
}); | |
const rateLimiterMiddleware = async (req, res, next) => { | |
try { | |
await rateLimiter.consume(req.connection.remoteAddress); | |
next(); | |
} catch (error) { | |
res.status(429).send("Too many requests. Please try again later."); | |
} | |
}; | |
server.listen(process.env.PORT || 3001, () => { | |
const { port } = server.address(); | |
console.log(`${new Date().toUTCString()} Server: Listening on port ${port}.`); | |
SocketManager(io); | |
}); | |
app.use(compression()); | |
app.use(rateLimiterMiddleware); | |
app.use(helmet()); | |
if (process.env.NODE_ENV === "development") { | |
app.use(cors({ origin: process.env.CLIENT_URL })); | |
} else { | |
app.use(express.static(path.join(__dirname, "client/dist"))); | |
app.get("*", (req, res) => { | |
res.sendFile(path.join(__dirname, "client/dist", "index.html")); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment