šŸ“• Build AI Agents using LangGraph.js is now out!

Replace the browser URL when a user clicks on a NextJs Link

If we want to change/customize the URL shown in the browser when a user clicks on a Link component we can use the as property:

<Link href="/cats" as="/someurl">
    <a>Go to the cats gallery</a>
</Link> 

So, even if the href of the Link component is set to /cats when the user clicks on that link we will have the following URL in the browser:

http://localhost:3000/someurl

This allows us to have urls that don't have a corespoding file in the /pages folder.

We can use the as property even if we have a query params for our routes.

One usecase will be to get more cleaner urls:

<Link href={{
          pathname: '/product/[id]',
          query: { id: '1' }
        }} as="/p/1">
        <a>Link to product /1</a>
</Link>

Keep in mind that there are two sides to the story. The client-side navigation and the server-side one. This means that if we directly paste the http://localhost:3000/someurl URL in the address bar of the browser and hit enter we will get a 404 error page. We will get the same error if someone shares the url via a link, of if its bookmaked. This happens because the /someurl URL does not actually exist. If we want this to work we will need to customize the behavior of the express NodeJs server where the app runs.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

Your email address will not be published. Required fields are marked *