MCPcopy Create free account
hub / github.com/github/docs / ClientSideRedirectExceptions

Function ClientSideRedirectExceptions

components/ClientSideRedirectExceptions.tsx:16–68  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

14// /rest/reference/repos#statuses to
15// /rest/reference/commits#commit-statuses)
16export default function ClientSideRedirectExceptions() {
17 const router = useRouter()
18 useEffect(() => {
19 // Because we have an async call to fetch, it's possible that this
20 // component unmounts before we perform the redirect, however, React
21 // will still try to perform the redirect even after the component
22 // is unmounted. To prevent this, we can use the AbortController signal
23 // to abort the Web request when the component unmounts.
24 const controller = new AbortController()
25 const signal = controller.signal
26
27 const { hash, pathname } = window.location
28 // path without a version or language
29 const barePath = pathname
30 .replace(`/${router.locale}`, '')
31 .replace(`/${router.query.versionId || ''}`, '')
32
33 async function getRedirect() {
34 try {
35 const sp = new URLSearchParams()
36 sp.set('path', barePath)
37 sp.set('hash', hash.replace(/^#/, ''))
38
39 // call the anchor-redirect endpoint to get the redirect url
40 const response = await fetch(`/anchor-redirect?${sp.toString()}`, {
41 signal,
42 })
43
44 // the response status will always be 200 unless there
45 // was a problem with the fetch request. When the
46 // redirect doesn't exist the json response will be empty
47 if (response.ok) {
48 const { to } = await response.json()
49 if (to) {
50 // we want to redirect with the language and version in tact
51 // so we'll replace the full url's path and hash
52 const fromUrl = pathname + hash
53 const bareUrl = barePath + hash
54 const toUrl = fromUrl.replace(bareUrl, to)
55 router.replace(toUrl)
56 }
57 }
58 } catch (error) {
59 console.warn('Unable to fetch client-side redirect:', error)
60 }
61 }
62 getRedirect()
63
64 return () => controller.abort()
65 }, [])
66
67 return null
68}

Callers

nothing calls this directly

Calls 1

getRedirectFunction · 0.70

Tested by

no test coverage detected