reactjsauthenticationpostnext.jsjwt

How to prevent user credentials showing on URL after logging in in NextJS?


I want the user to log in and direct it to the homepage, instead the credentials of the user are showing in the URL like so: http://localhost:3000/auth/login?email=test%40gmail.com&password=test.

The token is being created correctly, but the redirecting is not working correctly. This is the handleSubmit function:

 const [state, setState] = useState({
    email: "",
    password: "",
  });
 async function handleSubmit() {
    console.log(state);
    const res = await fetch(LOGIN_API_BASE_URL, {
      method: "POST",
      body: JSON.stringify(state),
      headers: {
        "Content-Type": "application/json",
        credentials: "omit",
      },
    });
    if (res.ok) {
      const json = await res.json();
      localStorage.setItem("token", json.token);
      router.push("/"); 
    } else {
      alert("Bad credentials");
    }
  }

I am using Java JWT to create the token and handling it with NextJS in the front end part.

I tried every solution possible and nothing did not work yet, I am guessing the back-end code is written correctly since the token is being created. The state values if shown in the console are written like so:

{email:"test@gmail.com", password: "test"}


Solution

  • That's the normal behaviour of your application. You need to manually prevent it. Pass the event from the button in the handleSubmit() function and call preventDefault() method.

    So, in your button you'll do this,

    <button onClick={(event) => handleSubmit(event)}>
    </button>
    

    And modify your code to call preventDefault()

    async function handleSubmit(event) {
        evnet.preventDefault();
        console.log(state);
        // rest of your code
      }