Next.js, how to open a link in a new window
By Flavio Copes
Learn how to open a link in a new window in Next.js by adding a target attribute set to _blank on the inner a tag while href stays on the Link component.
Here’s how you can open a link in a new window in Next.js: add target="_blank" to the inner a tag, while the href stays on the Link component:
<Link href={url}>
<a target="_blank">Click this link</a>
</Link>
You first wrap the a tag in a Link component (the Link component provided by Next.js), and inside the a tag you add a target="_blank" attribute, just like you’d do in plain HTML.
The href attribute stays on the Link component, to play well with client-side routing.
Why is the target on the a tag and not on Link?
Link is a routing component. It intercepts the click and tells the Next.js router to navigate without a full page reload. It passes the href down to the a tag it wraps, but it’s not the element the browser actually renders.
The a tag is what ends up in the HTML. Anything the browser needs to see, like target, rel or a className, belongs there.
Putting target="_blank" on Link instead of the a tag does nothing. Link doesn’t forward it, so the link keeps opening in the same window. If your new-window link is not working, this is the first thing to check.
Add rel=“noopener noreferrer”
When you open a link in a new window, my advice is to also add a rel attribute:
<Link href={url}>
<a target="_blank" rel="noopener noreferrer">
Click this link
</a>
</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.
What about external links?
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.
Related posts about next: