1
1
"use client" ;
2
+
3
+ const getBasePath = ( ) => {
4
+ const raw = process . env . NEXT_PUBLIC_BASE_URL ?? "" ;
5
+ const trimmed = raw . replace ( / ^ \/ + | \/ + $ / g, "" ) ; // strip leading/trailing slashes
6
+ return trimmed ? `/${ trimmed } /` : "/" ; // ensure trailing slash
7
+ } ;
8
+
2
9
import React , { createContext , useContext , useEffect , useState } from "react" ;
10
+ import { useRouter } from "next/navigation" ; // ⟵ add this
3
11
4
12
type Flags = {
5
13
refactoredUIFlag : boolean ;
@@ -48,6 +56,8 @@ function writeFlagSafely(v: boolean) {
48
56
}
49
57
50
58
export const FeatureFlagsProvider = ( { children } : { children : React . ReactNode } ) => {
59
+ const router = useRouter ( ) ; // ⟵ add this
60
+
51
61
// Lazy init reads from localStorage only on the client
52
62
const [ refactoredUIFlag , setRefactoredUIFlagState ] = useState < boolean > ( ( ) => readFlagSafely ( ) ) ;
53
63
@@ -73,6 +83,21 @@ export const FeatureFlagsProvider = ({ children }: { children: React.ReactNode }
73
83
return ( ) => window . removeEventListener ( "storage" , onStorage ) ;
74
84
} , [ ] ) ;
75
85
86
+ // Redirect to base path the moment the flag is OFF.
87
+ useEffect ( ( ) => {
88
+ if ( refactoredUIFlag ) return ; // only act when turned off
89
+
90
+ const base = getBasePath ( ) ;
91
+ const normalize = ( p : string ) => ( p . endsWith ( "/" ) ? p : p + "/" ) ;
92
+ const current = normalize ( window . location . pathname ) ;
93
+
94
+ // Avoid a redirect loop if we're already at the base path.
95
+ if ( current !== base ) {
96
+ // Replace so the "off" redirect doesn't pollute history.
97
+ router . replace ( base ) ;
98
+ }
99
+ } , [ refactoredUIFlag , router ] ) ;
100
+
76
101
return (
77
102
< FeatureFlagsCtx . Provider value = { { refactoredUIFlag, setRefactoredUIFlag } } > { children } </ FeatureFlagsCtx . Provider >
78
103
) ;
0 commit comments