server.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const env = require("./env");
  2. const cookieParser = require("cookie-parser");
  3. const passport = require("passport");
  4. const express = require("express");
  5. const helmet = require("helmet");
  6. const morgan = require("morgan");
  7. const path = require("path");
  8. const hbs = require("hbs");
  9. const helpers = require("./handlers/helpers.handler");
  10. const renders = require("./handlers/renders.handler");
  11. const asyncHandler = require("./utils/asyncHandler");
  12. const locals = require("./handlers/locals.handler");
  13. const links = require("./handlers/links.handler");
  14. const routes = require("./routes");
  15. const utils = require("./utils");
  16. // run the cron jobs
  17. // the app might be running in cluster mode (multiple instances) so run the cron job only on one cluster (the first one)
  18. // NODE_APP_INSTANCE variable is added by pm2 automatically, if you're using something else to cluster your app, then make sure to set this variable
  19. if (env.NODE_APP_INSTANCE === 0) {
  20. require("./cron");
  21. }
  22. // intialize passport authentication library
  23. require("./passport");
  24. // create express app
  25. const app = express();
  26. // this tells the express app that the app is running behind a proxy server
  27. // and thus it should get the IP address from the proxy server
  28. // IMPORTANT: users might be able to override their IP address and this
  29. // might allow users to bypass the rate limit or lead to incorrect link stats
  30. // read the Kutt documentation to learn how prevent users from changing their real IP address
  31. app.set("trust proxy", true);
  32. app.use(helmet({ contentSecurityPolicy: false }));
  33. app.use(cookieParser());
  34. app.use(express.json());
  35. app.use(express.urlencoded({ extended: true }));
  36. app.use(express.static("static"));
  37. app.use(passport.initialize());
  38. app.use(locals.isHTML);
  39. app.use(locals.config);
  40. // template engine / serve html
  41. app.set("view engine", "hbs");
  42. app.set("views", path.join(__dirname, "views"));
  43. utils.registerHandlebarsHelpers();
  44. // if is custom domain, redirect to the set homepage
  45. app.use(asyncHandler(links.redirectCustomDomainHomepage));
  46. // render html pages
  47. app.use("/", routes.render);
  48. // handle api requests
  49. app.use("/api/v2", routes.api);
  50. app.use("/api", routes.api);
  51. // finally, redirect the short link to the target
  52. app.get("/:id", asyncHandler(links.redirect));
  53. // 404 pages that don't exist
  54. app.get("*", renders.notFound);
  55. // handle errors coming from above routes
  56. app.use(helpers.error);
  57. app.listen(env.PORT, () => {
  58. console.log(`> Ready on http://localhost:${env.PORT}`);
  59. });