'clean urls with router.push in nextjs
I have the code below. It redirects to /home and passes a username variable. However, in the address bar, it shows http://localhost:3000/home?username=bobmarley. How can I pass variables using next.js cleanly?
import { withRouter } from 'next/router'
loginUser(this.state.user)
.then(response => {
var username = response['username'];
if (username) {
this.props.router.push({
pathname: '/home',
query: { username: username }
});
}
});
Solution 1:[1]
Use the as prop of router.push, this will be what is displayed in the address bar. Set it to the same value used for pathname.
as- Optional decorator for the URL that will be shown in the browser.
this.props.router.push({
pathname: '/home',
as: '/home',
query: { username: username }
});
Solution 2:[2]
This is not where you put the as parameter. It should look like
this.props.router.push({
pathname: '/home',
query: { username: username }
},
{
pathname: '/masked-url'
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
| Solution 2 | Alokesh Bora |
