13

When I try to redirect using Router.push() I get the following error:

TypeError: next_router__WEBPACK_IMPORTED_MODULE_3__.Router.push is not a function

I am trying to migrate from create-react-app to next js.

const redirectUser = () => {
        if (true) {
            Router.push('/');
        }
    };
3
  • Did you try import Router by: import Router from 'next/router? Commented Mar 3, 2019 at 14:16
  • Yes I did import Commented Mar 4, 2019 at 0:19
  • 1
    Hah! I am actually following your udemy course mern-react-node-aws. Without this answer I was going to spend several thousands of years looking for the source of this error XD What a surprise to find the answer was provided by none other than Ryan Dhungel himself ^^ Thanks for all you do! Your course is helping me A LOT Commented Apr 30, 2021 at 17:07

4 Answers 4

58

I had to import like so:

// works
import Router from "next/router";
// dont
import { Router } from "next/router";
Sign up to request clarification or add additional context in comments.

3 Comments

That saved my day! Wouldn't have noticed it
Thanks a load, man. Was frustrated after giving my all for the continuous 5 hours.
The auto-importer defaults to the bad import. grrrr.
4

Don't add curly bracket while importing Router from next/router

Use this:

import Router from "next/router";

Comments

1

The Router module is available only client-side

1 Comment

so you mean one would need useEffect() from react
1

you have to take into account when you use next.js that the redirects should be in getInitialProps method in order to avoid unnecessary render components.

for example

const MyComponent = ()=>{
  return <tag> {/* ... */} </tag>
}
MyComponent.getInitialProps = ({res}) => {
  if (res) { 
    /* serve-side */
    res.writeHead(302, {
    Location: 'http://example.com'
  })
  res.end()
  } else {      
   /* client-side */
    Router.push('http://example.com')
  }
  return {}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.