server.js 2.1 KB

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