Managing embedded URLs in Next.js applications

I am currently in the process of developing an ecommerce platform, expecting users to utilize both our domain and their own custom domains. For example:

ourplatform.com/username

theirdomain.com

My goal is to customize the inline links based on the specific domain used to access the site. If it is our domain, the link structure should be /username/page, whereas for their domain, it should simply be /page.

Here is the code snippet I have created thus far, which only adds the username if the domain belongs to 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>
  )
}

However, I am encountering the following error message:

Error: Failed prop type: The prop `href` expects a `string` or `object` in `<Link>`, but got `undefined` instead.

How can I successfully define different href links based on the user's domain?

Answer №1

Ensuring proper evaluation of window.location is crucial during the client-side phase. However, to prevent the link constant from being set to undefined in the server-side compilation phase, it's essential for customPath() to return a value for the <Link /> component.

const customPath = ({ username }) => {
  if (typeof window !== 'undefined') {
    return window.location.hostname !== 'ourplatform.com' // include `.hostname`
      ? '/'
      : `/${username}`
  }
  return '/' // To ensure server-side compilation
}

Answer №2

Instead of directly checking typeof window !== 'undefined' to access window.location, I suggest handling the customPath logic within a useEffect function to avoid any server-side rendering discrepancies.

Below is a custom hook that manages the custom path logic without triggering errors or 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>
    )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

On IOS, the internal links within my PWA app are unexpectedly opening as external links

Manifest File (manifest.json): { "theme_color": "#202020", "background_color": "#ffffff", "display": "standalone", "orientation": "portrait", &quo ...

Tips for stopping links in iOS web applications from launching in a new Safari tab

I am in the process of developing an HTML application specifically for iPads. To enhance user experience, I have added the web app to the homescreen using the "favorite" option. However, I encountered an issue where every internal URL opens in a new Safari ...

Using JavaScript and jQuery to toggle visibility of a dynamically created input field

This script dynamically generates a group of elements consisting of four input fields. Once an element is created, you can select or deselect it, which will trigger the corresponding editor to appear. I have implemented a function to specifically hide the ...

Ways to decrease font size and insert a line break within a constrained input space?

I am facing an issue where the input box remains static with old numbers when it overflows, and newly typed numbers do not appear at all. <!DOCTYPE html> <html> <body> <input type="text" id="output-area" placehold ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

Filtering nested object properties by value using Java Script

I am seeking assistance in filtering nested Objects by property values, with a specific requirement involving values stored in an array. Despite previous similar inquiries, I have yet to find a solution tailored to cases like mine. In reviewing the code s ...

Preventing Shift: How to Only Replace the Chosen Vue Draggable Item Without Affecting Other Grid Items

Let's try an example to demonstrate: https://codesandbox.io/s/j4vn761455?file=/src/App.vue:112-116 Step 1: Drag item 4 to where 5 is. Notice how 4 and 5 switch positions. Step 2: Now, drag item 1 to position 6. Watch as 1 moves to where 6 was, pushi ...

ReactJs throws an error of "Uncaught SyntaxError: Unexpected token '<' while utilizing the map() function in ReactJs that produces JSX (specifically MaterialUi-icons) within an array

In the file constant.js, I have defined object names and icons as keys. The key icon contains the icon component from @mui/icons-material, but when I attempt to retrieve the value from the icon, I encounter an error. Uncaught SyntaxError: Unexpected toke ...

Sending a variable to a template in AngularJS

I am looking for a way to pass a variable or text to a template in order to display the value within my template. While browsing through resources, I found an example on jsFiddle that demonstrates this functionality using ng-repeat. However, I am curious ...

Modifying Div Size with Jquery

I am working on populating the div container with square boxes, but I'm having trouble adjusting the size of my #gridSquare div. Despite trying to change its height and width using jQuery, it doesn't seem to work as expected. $('#gridSquare ...

Ensuring security against cross site scripting attacks on window.location.href

Currently, I'm utilizing window.location.href to redirect the page to an external URL: <Route exact path={rootUrl} component={() => { window.location.href =`https://${window.location.hostname}/www/testurl?google=true`; return null; }} /> How ...

Loading New Page When Iframe is Loaded

I am currently working with an iframe that reflects the appscript I have created. Is there a way to automatically redirect the user to a different page when they change a link or submit a form within the iframe? <div class="embed-responsive em ...

Exploring the power of Next JS by implementing server-side rendering with a

I am faced with the challenge of incorporating navigation into my layout by utilizing data from an API and then displaying it on specific pages. The catch is that the Layout file is not located in the pages folder, meaning I cannot use traditional getStati ...

There was an error: "TypeError: Unable to access the equipmentImage property of

Help needed! I am encountering a strange error while trying to upload an equipment image from postman as form data. The error states: Type Error; Cannot read property equipmentImage. I am using express-fileupload for the image upload process. Can someone ...

Uncovering the jsPlumb link between a pair of identifiers

Could someone help me understand how to disconnect two HTML elements that are connected? I have the IDs of both elements, but I'm not sure how to locate their connection in the jsPlumb instance. Any tips on finding the connection between two IDs? ...

jQuery's show/hide functionality allows for the dynamic resizing of images,

I am experiencing an issue with a Joomla template that has a custom jQuery menu. When I hover over the map with my mouse, the overlay appears slightly larger than expected. This problem seems to be occurring in Firefox and IE 11, leading me to believe it ...

Retrieving JSON data from two different URLs and processing it in the same Android activity

This is the code snippet: @Override protected DVLAInformation doInBackground(String... params) { try { Intent intent = getIntent(); String dvlaNumFin = intent.getStringExtra("dvlaNumber"); ...

Step-by-step guide on retrieving data from E-goi with REST API in Google Apps Script

Looking to extract data from the e-goi API, I found a .jar file in their documentation. Unfortunately, there are no examples provided for the REST API, leaving me unsure of how to access it directly. As I'm still new to programs like this, I could rea ...

Creating a webpage that seamlessly scrolls and dynamically loads elements

Currently, I am working on a dynamic website that loads new elements as you scroll down the page. Here is an example of the HTML code: <div>some elements here</div> <div id="page2"></div> And this is the JavaScript code: var dis ...

Leverage information stored in an array within the HandsonTable Angular directive

Some of my columns in a HandsoneTable created using Angular directives are not rendering when I try to use an array as the data source with common array notation (name[0]). I'm unsure if this is supposed to work like this or if I am doing something wr ...