Cloyd Abad
Cloyd Abad

Reputation: 737

How to push user to external (incomplete) URL. i.e google.com NEXTJS

Im trying to push a user to an external url but that problem is that the url is incomplete, for example it may look like this: google.com If I used link or even just an tag in Nextjs, it will only link the user to an internal page. I want the user to be redirected to an external page. Here is my Code:

<a href={`${data.link}`}>
    <div className={css.visitLinkContainer}>
        Visit Link
    </div>
</a>

The data.link may have a url that is incomplete like this: google.com. How can I go around this problem?

Upvotes: 2

Views: 408

Answers (2)

Sean W
Sean W

Reputation: 6598

By default, browsers use relative URLs. You can tell the browser to use an implicit protocol by prepending //.

<a href={`//${data.link}`}>Visit Link</a>

If some of your URLs can contain the protocol (http[s]) you will need to remove it first.

const href = new URL(data.link).host;
<a href={`//${href}`}>Visit Link</a>

Additional considerations when linking to external domains - if you link to an external domain and use target="_blank" you should also set rel="noreferrer" to protect your user's privacy and increase site security.

Upvotes: 2

geobudex
geobudex

Reputation: 566

You could consider using nextjs-redirect libray

Upvotes: 0

Related Questions