_app.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import App, { AppContext } from "next/app";
  2. import { StoreProvider } from "easy-peasy";
  3. import getConfig from "next/config";
  4. import Router from "next/router";
  5. import decode from "jwt-decode";
  6. import cookie from "js-cookie";
  7. import Head from "next/head";
  8. import React from "react";
  9. import { initGA, logPageView } from "../helpers/analytics";
  10. import { initializeStore } from "../store";
  11. import { TokenPayload } from "../types";
  12. const isProd = process.env.NODE_ENV === "production";
  13. const { publicRuntimeConfig } = getConfig();
  14. // TODO: types
  15. class MyApp extends App<any> {
  16. static async getInitialProps({ Component, ctx }: AppContext) {
  17. const store = initializeStore();
  18. ctx.store = store;
  19. let pageProps = {};
  20. if (Component.getInitialProps) {
  21. pageProps = await Component.getInitialProps(ctx);
  22. }
  23. const token =
  24. ctx.req && (ctx.req as any).cookies && (ctx.req as any).cookies.token;
  25. const tokenPayload: TokenPayload = token ? decode(token) : null;
  26. if (tokenPayload) {
  27. store.dispatch.auth.add(tokenPayload);
  28. }
  29. return { pageProps, tokenPayload, initialState: store.getState() };
  30. }
  31. store: ReturnType<typeof initializeStore>;
  32. constructor(props) {
  33. super(props);
  34. this.store = initializeStore(props.initialState);
  35. }
  36. componentDidMount() {
  37. const { loading, auth } = this.store.dispatch;
  38. const token = cookie.get("token");
  39. const isVerifyEmailPage =
  40. typeof window !== "undefined" &&
  41. window.location.pathname.includes("verify-email");
  42. if (token && !isVerifyEmailPage) {
  43. auth.renew().catch(() => {
  44. auth.logout();
  45. });
  46. }
  47. if (isProd) {
  48. initGA();
  49. logPageView();
  50. }
  51. Router.events.on("routeChangeStart", () => loading.show());
  52. Router.events.on("routeChangeComplete", () => {
  53. loading.hide();
  54. if (isProd) {
  55. logPageView();
  56. }
  57. });
  58. Router.events.on("routeChangeError", () => loading.hide());
  59. }
  60. render() {
  61. const { Component, pageProps } = this.props;
  62. return (
  63. <>
  64. <Head>
  65. <title>
  66. {publicRuntimeConfig.SITE_NAME} | Modern Open Source URL shortener.
  67. </title>
  68. </Head>
  69. <StoreProvider store={this.store}>
  70. <Component {...pageProps} />
  71. </StoreProvider>
  72. </>
  73. );
  74. }
  75. }
  76. export default MyApp;