Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous url in nextjs

Tags:

next.js

How can I get the previous URL in nextjs? I thought the values this.props.router.asPath and nextProps.router.asPath are diffrent.

Actually, I want to call router.push after login. I know that router.back goes to the previous page. But it's possible to go to another site. The users having history stacks go to the previous page, the users not having history stacks go to / main page.

import { Component } from 'react'
import App, { Container } from 'next/app';
import ErrorComponent from '@/components/error'

export default class MyApp extends App {
  render() {
    console.log(this.props)
    const { Component, pageProps, router } = this.props;
    const props = {
      ...pageProps,
      router
    }
    return (
      <ErrorBoundary>
        <Container>
          <Component {...props} />
        </Container>
      </ErrorBoundary>
    );
  }

  componentWillReceiveProps(nextProps) {
    // previous page url /contents
    console.log(this.props.router.asPath) // /about
    console.log(nextProps.router.asPath) // /about
    console.log('window.history.previous.href', window.history.previous) // undefined
  }
}

How can I fix it? Or how can I get the previous URL to move page after login?

like image 603
kkangil Avatar asked Apr 08 '19 02:04

kkangil


People also ask

How do I get past Route response on my router?

To detect previous path in React Router, we can set the state property to an object with the location. pathname as the value. <Link to={{ pathname: "/nextpath", state: { prevPath: location.

Does NextJS use client side routing?

The Next. js router allows you to do client-side route transitions between pages, similar to a single-page application. A React component called Link is provided to do this client-side route transition.


2 Answers

You find the Referer ( so the previous URL ) in the context of getServerSideProps or any other Data fetching methods

as

    context.req.headers.referer  

example in code

    export async function getServerSideProps(context) {
      console.log(context.req.headers.referer)
    }
like image 149
Madjid Boudis Avatar answered Oct 12 '22 11:10

Madjid Boudis


I think you can implement a custom history in global state

Something like this

_app.js

import React from 'react';
import App, { Container } from 'next/app';

class MyApp extends App {
    static async getInitialProps({ Component, ctx }) {
        let pageProps = {};

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

        return { pageProps };
    }

    state = {
        history: [] // keep history items in state
    };

    componentDidMount() {
        const { asPath } = this.props.router;

        // lets add initial route to `history`
        this.setState(prevState => ({ history: [...prevState.history, asPath] }));
    }

    componentDidUpdate() {
        const { history } = this.state;
        const { asPath } = this.props.router;

        // if current route (`asPath`) does not equal
        // the latest item in the history,
        // it is changed so lets save it
        if (history[history.length - 1] !== asPath) {
            this.setState(prevState => ({ history: [...prevState.history, asPath] }));
        }
    }

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

        return (
            <Container>
                <Component history={this.state.history} {...pageProps} />
            </Container>
        );
    }
}

export default MyApp;

so then in your components you can navigate wherever you want within history

if (!history || !history.length) {
    router.push('/');
} else {
    router.push(history[history.length - 1]);
}

Hope this helps!

like image 25
iurii Avatar answered Oct 12 '22 11:10

iurii