server.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 the app is running behind a proxy server
  26. // and thus it should get the IP address from the proxy server
  27. // IMPORTANT: users might be able to override their IP address and this
  28. // might allow users to bypass the rate limit or lead to incorrect link stats
  29. // read the Kutt documentation to learn how prevent users from changing their real IP address
  30. app.set("trust proxy", true);
  31. app.use(helmet({ contentSecurityPolicy: false }));
  32. app.use(cookieParser());
  33. app.use(express.json());
  34. app.use(express.urlencoded({ extended: true }));
  35. app.use(express.static("static"));
  36. app.use(passport.initialize());
  37. app.use(locals.isHTML);
  38. app.use(locals.config);
  39. // template engine / serve html
  40. app.set("view engine", "hbs");
  41. app.set("views", path.join(__dirname, "views"));
  42. utils.registerHandlebarsHelpers();
  43. // if is custom domain, redirect to the set homepage
  44. app.use(asyncHandler(links.redirectCustomDomainHomepage));
  45. // render html pages
  46. app.use("/", routes.render);
  47. // handle api requests
  48. app.use("/api/v2", routes.api);
  49. app.use("/api", routes.api);
  50. // finally, redirect the short link to the target
  51. app.get("/:id", asyncHandler(links.redirect));
  52. // 404 pages that don't exist
  53. app.get("*", renders.notFound);
  54. // handle errors coming from above routes
  55. app.use(helpers.error);
  56. app.listen(env.PORT, () => {
  57. console.log(`> Ready on http://localhost:${env.PORT}`);
  58. });