1

Is there any way i can use or have access to nextRouter/history in nextjs getInitialProps function.

const ViewPost: NextPage<EditPostProps> = (props): React.ReactElement<void> => {
  const router = useRouter(); // works here 

}

ViewPost.getInitialProps = async (ctx: Context): Promise<EditPostProps> => {
  const router = useRouter(); // doesn't work 
  // ctx props doesn't have history
}
export default withRouter(ViewPost);

My api class receives history or router as a param hence the need for one, but i couldn't get access to one inside the getInitialProps. Pls is there anyway i can access it? Any help would be appreciated.

Nuru Salihu
  • 4,756
  • 17
  • 65
  • 116

2 Answers2

2

next/router is a client-side router therefore is not accessible during server-side rendering in getInitialProps.

Since Next.js 9.3 getInitialProps is not recommended.

You can redirect a user on server-side inside getServerSideProps:

import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async context => {
    context.res.writeHead(302, { Location: '/login' })
    context.res.end()
    return {props: {}}
}

Response (context.res) is an instance of Node.js http.ServerResponse class.

GetServerSideProps

http.ServerResponse

How to redirect user's browser URL to a different page in Nodejs?

Nikolai Kiselev
  • 6,201
  • 2
  • 27
  • 37
  • the reason why i need one is that, my api design so far has a fallback incase of error or unautheicated acces that redirect user to login page. In normal react, i simply use creatBrowserHistory() to be able to use history.push. I couldn't find equivalent of that in nextjs . It seems to me like i can't use history or router outside component in nextjs and hence the reason i want to pass it . – Nuru Salihu Apr 18 '20 at 16:29
  • @NuruSalihu, you can redirect a user or give any response within `getInitialProps` with `ctx.res` object, so you don't need a client-side router for it – Nikolai Kiselev Apr 18 '20 at 16:58
  • do you mean i can redirect to a certain route like login using ctx.res ? Can you please give example or explain further ? Thank you ? – Nuru Salihu Apr 18 '20 at 17:05
  • Your code yielded the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client . It would have been perfect otherwise. – Nuru Salihu Apr 19 '20 at 08:06
  • @NuruSalihu, try `getServerSideProps`. See the updated answer, I just tested it - it works. – Nikolai Kiselev Apr 19 '20 at 08:42
2

The router is a singleton. You can do:

import Router from 'next/router'

and then inside getInitialProps():

Router.push('/path');
Dmitry Minkovsky
  • 36,185
  • 26
  • 116
  • 160