Home > Software design >  Handling inline URLs with Next.js
Handling inline URLs with Next.js

Time:04-25

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?

CodePudding user response:

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
}

CodePudding user response:

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>
    )
}
  • Related