Next.js, how to open a link in a new window

By

Learn how to open a link in a new window in Next.js by passing target and rel straight to the Link component, which forwards them to the underlying a tag.

~~~

Here’s how you can open a link in a new window in Next.js: put target="_blank" on the Link component itself.

import Link from 'next/link'

<Link href={url} target="_blank">
  Click this link
</Link>

Since Next.js 13, Link renders the <a> itself and forwards props like target, rel, and className to it. You don’t wrap a child <a> anymore. Before version 13 you had to, and target went on that inner <a>.

The same Link component handles both same-tab and new-window links. Only the target changes.

Add rel=“noopener noreferrer”

When you open a link in a new window, my advice is to always set rel as well:

<Link href={url} target="_blank" rel="noopener noreferrer">
  Click this link
</Link>

Without noopener, the new page gets a reference to your page through window.opener, and a malicious page can use it to redirect your tab. noreferrer also avoids sending the referrer header. Modern browsers apply noopener implicitly with target="_blank", but being explicit costs nothing.

Link exists for internal navigation, where client-side routing gives you fast page transitions.

For a link to another site, there’s nothing to route. You can skip Link entirely and write a plain a tag:

<a href="https://flaviocopes.com" target="_blank" rel="noopener noreferrer">
  my blog
</a>

Same result, one less component. I use Link for pages inside the app, and plain a tags for everything that leaves it.

Tagged: Next.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about next: