Nextjs - How to Redirect to Another Page and Pass State

May 11, 2021


We have a page, for example a Form. And, upon submission we would want user to be redirected to some other page and pass some state or props so that that page can show some message or so.

Next.js Router - Pass State

  • First import withRouter
import { withRouter } from 'next/router'
  • Wrap your component export with withRouter
export default withRouter(EditUser);

Now in your component’s props, you have a router object.

Redirect to other Page and Pass State

I have a user edit form, and upon submission. I want user to be redirected to /user/<id> And, I want to show a message that edit has been successful.

  pathname: `/users/${}`,
  query: {success: true}

Here, I’m passing a query parameter to that page. So it will be:


Retrieve Value in Redirected Page

In my component jsx file, I want to show a bootstrap alert.

return (
      {props.router.query.success &&
        <div className="alert alert-success alert-dismissible fade show" role="alert">
        <Button type="button" className="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>

Note the props.router.query.success

Similar Posts

Latest Posts