Search code examples
reactjsnext.jsdynamic-urlnext-link

NextJS dynamic routing, is "as" really necessary?


Both links work exactly the same, do we really need to use the as, can't we use just the href?

import Link from 'next/link'

export default function () {
  return (<>
    <Link href="/someroute">
      <a>WithOUT as</a>
    </Link>

    <br />
    <br />

    <Link href="/[param]" as="/someroute">
      <a>With as</a>
    </Link>
  </>
  )
}

Solution

  • "as" is used to have a nicer url. for example, since you are in a dynamic route, that param can be something very crazy, maybe a mongodb id or any hash value

     // mongodb id
     /507f191e810c19729de860ea
    
     // maybe ipfs hash
     /mtwirsqawjuoloq2gvtyug2tc3jbf5htm2zeo4rsknfiv3fdp46a
    

    From early docs

    href is a file system path used by the page and it shouldn't change at runtime. as on the other hand, will be dynamic most of the time according to your needs.

    So when next.js navigates, to decide which page to render, it will look at the href but to decide which url to show the user, it will look at the as

    when "as" is helpful

    Let's say you have a DynamicPostComponent and you are passing post prop

     const DynamicPostComponent = ({post}) => {}
    

    Inside this component, you would tell next.js where to go in pages directory. so you use href

      // assume we have "pages/posts/[slug]" directory
      href="/posts/[slug]"
    

    now inside the page you need to read the id of blog so that you have to fetch the post to show the user. for this you use as

     as={`/posts/${post.slug}`
    

    Your Link compnent will look like this

     <Link href="/postss/[slug]" as={`/posts/${post.slug}`}>
        <a>
         
        </a>
      </Link>
    
     
    

    as is removed after v10. https://nextjs.org/blog/next-10

    Automatic Resolving of href: The as property is no longer needed on next/link