Search code examples
next.jsnext-routerdynamic-routing

NextJS redirect to other page without query params


I am able to successfully redirect the user on successful login to the relative dashboard page. However, the URI is pretty polluted in this case 'somedomain.com/v1/internal/salesman/dashboard?name=SomeName&email=someemail&uid=somenumber'. I was hoping to do something like redirect(<DashBoard someProps={someProps}/> instead of polluting the URI. Is it possible to achieve what I want in NextJS?

const onSubmit = async (e) => {
    e.preventDefault();
    
    const server_path = process.env.SERVER_ADDRESS;
    try{
      const res = await fetch(`${server_path}api/v1/internal/salesman/signin`, {
        method: 'post',
        headers: {
          'Accept': 'application/json, text/plain, */*',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({email: email.val, password: password.val})
      });
      if(await res.status === 200){
        const data = await res.json();
        router.push({pathname: '/internal/salesman/dashboard', query: {name: data.name, email: data.email, uid: data.uid}});
      }
    } catch(error){
      console.log(error);
    }
    
  }

Solution

  • You can specify the URL path as you've prefer it to be seen using the as argument.

    router.push

    router.push(url, as, options)
    

    as: UrlObject | String - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our previous docs to see how it worked. Note: when this path differs from the one provided in href the previous href/as behavior is used as shown in the previous docs.

    router.push(
      {
        pathname: '/internal/salesman/dashboard',
        query: {
          name: data.name,
          email: data.email,
          uid: data.uid,
        },
      },
      '/internal/salesman/dashboard',
    );
    

    If you want to actually redirect then you can use router.replace with the same arguments.