fridays / next-routes

Universal dynamic routes for Next.js
MIT License
2.47k stars 230 forks source link

Prevent page reload with browser back and forth buttons #261

Closed vaibhav-kona closed 1 year ago

vaibhav-kona commented 5 years ago

I am using next-redux-wrapper and the redux state is getting lost because of the full page reloads happening when navigating using browser back and forth buttons. How to disable this and let client side routing take place instead of making server requests each time ?

Gelio commented 5 years ago

I ran into the same issue.

You may want to override next.js' App component and provide the Router that comes from next-routes, like so:

// pages/_app.tsx

import App, { Container, NextAppContext } from 'next/app';
import * as PropTypes from 'prop-types';
import React from 'react';

import { routes } from '../routes';

export default class CustomApp extends App {
  public static childContextTypes = {
    router: PropTypes.object,
  };

  public static async getInitialProps({ Component, ctx }: NextAppContext) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

  public getChildContext() {
    return {
      router: routes.Router,
    };
  }

  public render() {
    const { Component, pageProps } = this.props;

    return (
      <Container>
        <Component {...pageProps} />
      </Container>
    );
  }
}

Keep in mind this is Typescript, so if you are writing in plain Javascript the syntax will be slightly different, but I hope you get the idea.

This makes it so that the page is not reloaded when using the browser's back and forward buttons. I am still having problems when the user manually edits the slug in url, though.