Getting domain during SSR #207

Closed
opened 2025-08-09 17:15:24 +00:00 by fergalmoran · 0 comments
Owner

Originally created by @AleksandrAlbert on 1/26/2018

I am writing an app building on the React + Redux SPA which has a client and an api at different domains, something like this:

[local]
localhost:5000 (client)
localhost:5001 (api)

[web]
app.domain.com (client)
api.domain.com (api)

Now, when writing my fetch requests, I'd like to be able to send requests to the localhost api when I make requests from the localhost client, and the web api when requested from the web client. To do this, I have to be able to set my base url, so I am trying to write a getApiDomain method which I can use to pick the right domain.

let fetchTask = fetch(`${Domain.getApiDomain()}/api/Item/${id}`)...

My method looks like this:

export abstract class Domain {
    public static isLocalhost = Boolean(window.location.hostname === 'localhost' );

    public static getApiDomain(): string {

        return this.isLocalhost
            ? "http://localhost:5001"
            : "http://api.domain.com";
    }
}

This works well for the client, but I can't get it to work on the server during SSR due to the use of window. How can I get the hostname while executing on the server?

*Originally created by @AleksandrAlbert on 1/26/2018* I am writing an app building on the React + Redux SPA which has a client and an api at different domains, something like this: [local] localhost:5000 (client) localhost:5001 (api) [web] app.domain.com (client) api.domain.com (api) Now, when writing my fetch requests, I'd like to be able to send requests to the localhost api when I make requests from the localhost client, and the web api when requested from the web client. To do this, I have to be able to set my base url, so I am trying to write a `getApiDomain` method which I can use to pick the right domain. ``` let fetchTask = fetch(`${Domain.getApiDomain()}/api/Item/${id}`)... ``` My method looks like this: ``` export abstract class Domain { public static isLocalhost = Boolean(window.location.hostname === 'localhost' ); public static getApiDomain(): string { return this.isLocalhost ? "http://localhost:5001" : "http://api.domain.com"; } } ``` This works well for the client, but I can't get it to work on the server during SSR due to the use of `window`. How can I get the hostname while executing on the server?
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github/JavaScriptServices#207
No description provided.