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

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...

npm installs a multitude of dependencies

Recently, I purchased an HTML template that includes various plugins stored in a directory named bower_components, along with a package.js file. While trying to add a new package that caught my interest, I opted to utilize npm for the task. Upon entering ...

Steps for adding a favicon to Content-Type: application/json

In my implementation using node.js, I have an API that returns a response with Content-Type: application/json. Here is an example: module.exports={ api: (req, res) => { let data = {"data": [1, 2, 3]}; res.status(200).json(d ...

trigger the focusout event within the focusin event

I am attempting to trigger the focusout event within the focusin event because I need to access the previous value from the focusin event, but the focusout event is being triggered multiple times. $('tr #edituser').focusin(function(){ var ...

Unable to launch React Native project

Error: Module Not Found Cannot find module 'C:\Users\Admin\AppData\Local\npm-cache\_npx\7930a8670f922cdb\node_modules\@babel\parser\lib\index.js'. Please make sure that your package.jso ...

Issue with JavaScript: Flag set to false does not halt the simple animation

My goal is to initiate animations when the mouse is pressed down and then immediately halt them once the mouse is released. Upon pressing the mouse, I set a flag to true which triggers the animation of the corresponding button that was clicked. However, t ...

Running a React application through a personalized Express server, all the while ensuring seamless automatic updates throughout the development

I currently have a React application along with a completely distinct Express server application. To serve my React app using a customized express server, I utilize the following code within my Express app: app.get("*", (req, res) => { res. ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

Stellar for occasions that don't come around often

Is it worth utilizing a Comet for events that do not require real-time updates, but can have a delay of around 1 minute? Examples could include: updates on Twitter statuses notifications on Facebook While Comet is commonly used in chat applications (suc ...

Exploring NextJs API routes: Understanding the distinction between 2 POST requests

I'm currently working on an app using NextJS and I've encountered a challenge. In one of the pages, I need to implement functionality for buying, selling, and deleting assets. However, I'm unsure how to differentiate between buy and sell req ...

What could be causing my default prop to not be transmitted to the child component in vuejs2?

Having trouble passing a default value to my Leaflet map child component before fetching the desired data from an API endpoint. I tried using country coordinates like latitude and longitude, but it's not working as expected. This is how I attempted t ...

Display the div only when the radio button has been selected

I have been attempting to tackle this issue for quite some time now, but unfortunately, I haven't had any success. My goal is to display a specific div on the webpage when a particular radio button is selected. While I have managed to achieve this by ...

JSON returning issue with date formatting

After converting a date to a string using ToString("d") in C# and then serializing it into JSON for the client, I'm encountering an issue where instead of displaying the formatted date on the page, I see the following literal text: /Date(-62135575200 ...

React - Issue with Input event handling when utilizing both onChange and onKeyDown functions

I was attempting to create a feature similar to a multi-select, where users could either choose a value from a list or enter a new value. The selected value should be added to an array when the user presses the enter key. To monitor changes in the input ...

Adjust the position of an element based on changes in window size using jQuery

Wondering if this question is unique, as I've spent quite some time searching for a solution to this issue without any luck. Perhaps my search criteria aren't correct. I have a navigation bar that becomes fixed when it reaches the top of the vie ...

Generate a div element dynamically when an option is selected using AngularJS

I'm having trouble dynamically creating div elements based on the selected option value, but for some reason ng-repeat isn't working as expected. Can you help me figure out what I'm missing? Here's the HTML snippet I'm using - &l ...

Create a log table specifically for tracking changes made to the drop-down menu

I need to create a Change log table that will track any changes made in the drop-down menu. For instance, I am working on a worksheet with a select menu called Results which includes options like Positive, Negative, Unknown. I want the system to log any ch ...

Utilizing Smart Table for Data Binding with JSON Dataset

I need help binding a JSON file to a smart table. How can I use the loop function for iteration? The design of the smart table is displaying, but the data from the JSON file is not binding. Here is the JSON file: [ { "year": 2013, "id ...

The seamless integration of Next.js and Socket.IO enhances real-time

Hello, I hope you're having a great day! Currently, I'm diving into Socket.IO with the help of online tutorials. However, I've encountered a roadblock in my learning journey. The tutorial shows everything working fine, but when I try it out ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...