0

I want to display pages with different states based on different query params in next.js , so that when a user uses a link with query param , It should not show the default page , but based on the state.

For simplicity Coinsider the home page as localhost:3000 This renders some default text 'Hello user' If user enters localhost:3000/?name=JohnDoe This should render Hello JohnDoe.

Things I have tried . I am able to add the query param using event handler's via next router . router.push('/?name=JohnDoe) But I dont know of a solution to set the state when the user enters the page directly using the a link with query params

Hussam Khatib
  • 600
  • 6
  • 17

2 Answers2

0

You can access the query in getServerSideProps and then redirect or do whatever you want with that query :

const getServerSideProps = (ctx) => {
   const {params} = ctx;
   
   if(params){
     return {
        redirect: {
        permanent: false,
        destination: "/login",
     }
   }
}
Mehdi Faraji
  • 2,574
  • 8
  • 28
  • 76
0

To read query params, you should use router.query.

Here is an example that would render 'Hello user' on localhost:3000, and 'Hello JohnDoe' on localhost:3000?name=JohnDoe

import { useRouter } from 'next/router';

const Page = () => {
  const router = useRouter();

  const userName = router.query.name ?? 'user';

  return <div>Hello {userName}</div>;
};

export default Page;