'Handling inline URLs with Next.js
I'm building an ecommerce platform where users will be using both our domain and their own domains like below.
ourplatform.com/username
theirdomain.com
I'd like to set the inline links depend on the domain they're entering the site. If it's our domain it should be /username/page or if it's their domain it should be just /page.
This is what I have so far. Only adding username if the domain is our platform.
import Link from 'next/link'
const customPath = ({ username }) => {
if (typeof window !== 'undefined') {
return window.location !== 'ourplatform.com'
? '/'
: `/${username}`
}
}
export default ({ username }) => {
const link = customPath({ username })
return (
<Link href={link}>
Home
</Link>
)
}
But I'm getting this error.
Error: Failed prop type: The prop `href` expects a `string` or `object` in `<Link>`, but got `undefined` instead.
How can I set different href links for different domains?
Solution 1:[1]
You're correctly limiting the evaluation of window.location to the client-side phase, but you'll still need to have customPath() return a value for the <Link /> component during the server-side compilation phase. Without a returned value, the link constant will be set to undefined.
const customPath = ({ username }) => {
if (typeof window !== 'undefined') {
return window.location.hostname !== 'ourplatform.com' // include `.hostname`
? '/'
: `/${username}`
}
return '/' // return something to satisfy server-side compilation
}
Solution 2:[2]
Rather than directly using typeof window !== 'undefined' to access window.location, I'd recommend you handle the customPath logic inside a useEffect to prevent server-side rendering mismatches.
Here's a custom hook that handles the custom path logic, without throwing any errors/warnings.
import Link from 'next/link'
function useCustomPath({ username }) {
const [customPath, setCustomPath] = useState('/') // Default path during SSR
useEffect(() => {
const path = window.location.hostname !== 'ourplatform.com' ? '/' : `/${username}`
setCustomPath(path) // Set appropriate path on the client-side
}, [username])
return customPath
}
export default ({ username }) => {
const link = useCustomPath({ username })
return (
<Link href={link}>
Home
</Link>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark G |
| Solution 2 | juliomalves |
