server.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 path = require("path");
  7. const hbs = require("hbs");
  8. const helpers = require("./handlers/helpers.handler");
  9. const renders = require("./handlers/renders.handler");
  10. const asyncHandler = require("./utils/asyncHandler");
  11. const locals = require("./handlers/locals.handler");
  12. const links = require("./handlers/links.handler");
  13. const routes = require("./routes");
  14. const utils = require("./utils");
  15. // run the cron jobs
  16. // the app might be running in cluster mode (multiple instances) so run the cron job only on one cluster (the first one)
  17. // 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
  18. if (env.NODE_APP_INSTANCE === 0) {
  19. require("./cron");
  20. }
  21. // intialize passport authentication library
  22. require("./passport");
  23. // create express app
  24. const app = express();
  25. // this tells the express app that it's running behind a proxy server
  26. // and thus it should get the IP address from the proxy server
  27. if (env.TRUST_PROXY) {
  28. app.set("trust proxy", true);
  29. }
  30. app.use(helmet({ contentSecurityPolicy: false }));
  31. app.use(cookieParser());
  32. app.use(express.json());
  33. app.use(express.urlencoded({ extended: true }));
  34. // serve static
  35. app.use("/images", express.static("custom/images"));
  36. app.use("/css", express.static("custom/css", { extensions: ["css"] }));
  37. app.use(express.static("static"));
  38. app.use(passport.initialize());
  39. app.use(locals.isHTML);
  40. app.use(locals.config);
  41. // template engine / serve html
  42. app.set("view engine", "hbs");
  43. app.set("views", [
  44. path.join(__dirname, "../custom/views"),
  45. path.join(__dirname, "views"),
  46. ]);
  47. utils.registerHandlebarsHelpers();
  48. // if is custom domain, redirect to the set homepage
  49. app.use(asyncHandler(links.redirectCustomDomainHomepage));
  50. // render html pages
  51. app.use("/", routes.render);
  52. // handle api requests
  53. app.use("/api/v2", routes.api);
  54. app.use("/api", routes.api);
  55. // finally, redirect the short link to the target
  56. app.get("/:id", asyncHandler(links.redirect));
  57. // 404 pages that don't exist
  58. app.get("*", renders.notFound);
  59. // handle errors coming from above routes
  60. app.use(helpers.error);
  61. app.listen(env.PORT, () => {
  62. console.log(`> Ready on http://localhost:${env.PORT}`);
  63. });