How to get current url programmatically?

how to get current client app url programmatically? so when it's on local, it will shows localhost and port, and if it is deployed , it will shows the current url, is there any exsisting hook to achieve this ? or should I build it from scratch?
2 Replies
kapa.ai
kapa.ai2mo ago
Hi @regn. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To get the current URL programmatically in a refine application, you can use the useApiUrl hook provided by refine. However, it's important to note that this hook returns the API URL, not the client app URL. For getting the client app URL, refine doesn't provide a specific hook out of the box. You would need to build this functionality yourself using the browser's window.location object. Here's how you can approach this: 1. For the API URL, you can use the useApiUrl hook:
import { useApiUrl } from "@refinedev/core";

const apiUrl = useApiUrl();
import { useApiUrl } from "@refinedev/core";

const apiUrl = useApiUrl();
This will return the API URL as configured in your data provider useApiUrl hook (https://refine.dev/docs/data/hooks/use-api-url/). 2. For the client app URL, you can create a custom hook:
import { useState, useEffect } from 'react';

const useClientUrl = () => {
const [clientUrl, setClientUrl] = useState('');

useEffect(() => {
if (typeof window !== 'undefined') {
setClientUrl(window.location.origin);
}
}, []);

return clientUrl;
};
import { useState, useEffect } from 'react';

const useClientUrl = () => {
const [clientUrl, setClientUrl] = useState('');

useEffect(() => {
if (typeof window !== 'undefined') {
setClientUrl(window.location.origin);
}
}, []);

return clientUrl;
};
You can then use this custom hook in your components:
const clientUrl = useClientUrl();
const clientUrl = useClientUrl();
This will give you the current client app URL, whether it's running locally (e.g., <http://localhost:3000>) or deployed (e.g., <https://your-deployed-app.com>). Remember that the client-side URL detection will only work in the browser environment, not during server-side rendering. That's why we use the useEffect hook to ensure the code runs only on the client side. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@336843331416096768> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?