remix-run / react-router

Declarative routing for React

Home Page:https://reactrouter.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Bug]: Cloudflare Pages - Outlet not working.

NeikiDev opened this issue · comments

What version of React Router are you using?

^6.22.3

Steps to Reproduce

I am using an normal createReactRouter, and since today it just doesnt work after i run the build command.

Expected Behavior

Using Routes, it just shows the 404 Error not found page, anything else is just a blank page,
I changed nothing on the Routing part or whatever, i just redeployed to cloudflare pages

Actual Behavior

Just blank page.

Main.ts

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Routes />
  </React.StrictMode>,
)

Routes.tsx

export const ANDRoutes = [
    {
        path: '/',
        index: true,
        element: <Home />
    },
    {
        path: "/upload",
        element: <Home />
    },
    {
        path: '*',
        element: <NotFound />
    }
]

const router = createBrowserRouter([
    {
        path: '/',
        element: <App />,
        children: ANDRoutes,
        errorElement: <ErrorPage />
    }
])

export function Routes() {

    return (
        <>
            <RouterProvider router={router} />
        </>
    )
}

App.tsx

function App() {
  
  return (
    <Box>
      <Outlet/>
    </Box>
  )
}

export default App

And home.tsx and the others returns valid Elements,
If i remove the Outlet and just use static my it displays that,
if i use use nothing appears just a blank white page, no errors nothing

When i just use npm run dev, so locally dev build it actually works, but when i run the build command to build the html, js etc it doesnt work anymore.

Changed it to

return (
        <SnackbarProvider maxSnack={3} preventDuplicate>
            <BrowserRouter>
                <Routes>
                    {
                        ANDRoutes.map((route, index) => {
                            return <Route key={index} path={route.path} element={route.element} errorElement={<ErrorPage />} />
                        })
                    }
                </Routes>
            </BrowserRouter>
        </SnackbarProvider>
    )

Now it works, but why not like before?

+1

This was so frustrating to debug. There went my entire morning. 😥

Using Vite.

import { createBrowserRouter, Outlet, RouterProvider } from "react-router-dom";

const newRouter = createBrowserRouter([
  {
    path: "/",
    element: <Outlet />, // <-- Culprit!
    children: [
      {
        index: true,
        element: <div>Success!</div>, // <-- Removes this element in build
      },
    ],
  },
]);

export default function App() {
  return <RouterProvider router={newRouter} />;
}

I want to add the actuall Error you get when using the built app on production.
Any page other than the actually "index" of the page shows the exact same with that error:

"Error: No route matches URL \"/reports/ds\""
"Error: No route matches URL "/reports/ds" at wr"
"internal: true"
"status: 404"
"statusText: "Not Found""

Not sure if related, but Outlet component is not working when built and on Vercel too with newest Vite (everything works when run with vite dev)

repo: https://github.com/danilo-89/react-error-boundary-research

import { Routes as ReactRoutes, Route } from 'react-router-dom';

// Layouts
import Layout from '../layouts/Layout';

// Components
import NoMatch from '../pages/NoMatch';
import Home from '../pages/Home';
import About from '../pages/About';
import RouteErrorBoundary from '../components/errorHandling/RouteErrorBoundary';

const Routes = () => {
	return (
		<>
			<ReactRoutes>
				<Route path='/' element={<Layout />}>
					{/* HOME */}
					<Route index element={<Home />} />

					{/* ABOUT */}
					{/* Route with Error Boundary */}
					<Route
						path='/about'
						element={
							<RouteErrorBoundary>
								<About />
							</RouteErrorBoundary>
						}
					/>

					{/* 404 */}
					<Route path='*' element={<NoMatch />} />
				</Route>
			</ReactRoutes>
		</>
	);
};

export default Routes;
import { Link, Outlet } from 'react-router-dom';

export default function Layout() {
	return (
		<>
			<nav className='absolute top-0 left-0 w-full p-5 bg-[#1a1a1a]'>
				<Link to='/'>Home</Link> | <Link to='/about'>About</Link>
			</nav>
			<div className='pt-10'>
				<Outlet />
			</div>
		</>
	);
}

+1 same problem. It stopped working randomly with vite build. Our production project was working fine until yesterday. package.json has fixed versions (without ˆ)

+1 when using Outlet for layout, i try remove it then build the routing logic work normaly without the layout

+1 same problem. It stopped working randomly with vite build. Our production project was working fine until yesterday. package.json has fixed versions (without ˆ)

Same here. I have a build on Netlify fully working from over a month ago. Now the same build with all the exact same dependency versions breaks. So odd.

I think this might have something to do with a recent update to Vite (or one of its transitive dependencies somewhere)?

I created two projects — the only difference between them is one uses vite@4, the other vite@5.

vite@4:
https://stackblitz.com/edit/react-router-outlet-with-vite-4

vite@5:
https://stackblitz.com/edit/react-router-outlet-with-vite-5

Both will look fine at first because the dev servers are running. Stop the dev servers then build/preview them instead. You'll see that in the vite@5 version the main content (<Outlet />) is missing and trying to navigate to the "About" page errors-out.

+1. Actually nested didn't work for me at all after I built it, only in dev. The fix was un-nesting and passing {children}.

+1. Actually nested didn't work for me at all after I built it, only in dev. The fix was un-nesting and passing {children}.

i use the same fix (we broke the production without image backup) took us all day

This might be due to rollup (or something else in the pipeline?) transforming

function flattenRoutes<
  RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject
>(
  routes: RouteObjectType[],
  branches: RouteBranch<RouteObjectType>[] = [],
  parentsMeta: RouteMeta<RouteObjectType>[] = [],
  parentPath = ""
): RouteBranch<RouteObjectType>[] {
  ...
}

into

function flattenRoutes(routes, branches, parentsMeta, parentPath) {
  {
    branches = [];
  }
  ...
  }

and leading to no matched nested routes in every case.

Maybe this is not even the same problem, but just in case, try reverting to older vite/rollup versions?

I'm using Yarn, and a temp fix for that issue is:

package.json:

"resolutions": {
    "rollup": "4.15.0"
}

It seems to be this commit rollup/rollup#5443

I'm convinced this PR is causing the issue we are running into: rollup/rollup#5443 (comment)

Definitely a compiler bug, not a React Router bug.

I'm using Yarn, and a temp fix for that issue is:

package.json:

"resolutions": {
    "rollup": "4.15.0"
}

It seems to be this commit rollup/rollup#5443

you save my day

I have the same issue with the Outlet the Bug appears after updating the react-router package, it took me all day to figure it out but finally, I solved the issue in my Code.

the Code that isn't working for me :

// ./src/App.jsx
return (
 <BrowserRouter>
            <Routes>
              <Route path="/" element={<Layout />}>
                <Route index element={<Home />} />
                {routes.map(({ element, path, id }) => (
                  <Route
                    key={id}
                    exact={true}
                    path={path}
                    element={createElement(element)}
                  />
                ))}
                <Route path="/*" element={<NotFound />} />
              </Route>
            </Routes>
          </BrowserRouter>
)

and i was using the <Outlet /> in the <Layout /> so...

// ./src/layout/index.jsx
         return (
                  <Navbar />
                       <Outlet />
                  <Footer />
        );

i passed the <Routes> for the <Layout/> as a children props and removed the <Outlet /> from it, chaging my code to

// ./src/App.jsx
return (
  <BrowserRouter>
         <Layout>
            <Routes>
              <Route index element={<Home />} />
              {routes.map(({ element, path, id }) => (
                <Route
                  key={id}
                  exact={true}
                  path={path}
                  element={createElement(element)}
                />
              ))}
              <Route path="/*" element={<NotFound />} />
            </Routes>
          </Layout>
  </BrowserRouter>
)
// ./src/layout/index.jsx
const Layout = ({children})=> {

         return (
                  <Navbar />
                       {children}
                  <Footer />
        );
}

I think this is the same method NextJS is using in Layout also

NOTE: This was a temporary solution but brophdawg11 soultion is more easier & effective

I'm using Vite5, and a temp fix for that issue is:

If you using npm, add to package.json file:

"overrides": {
    "rollup": "4.15.0"
}

If you using pnpm, add to package.json file:

"pnpm": {
    "overrides": {
        "rollup": "4.15.0"
    }
}

same here

<Route element={<ProtectPublicRoute />}>
                    <Route path="/onboarding/*" element={
                        <Suspense fallback={<Spinner color='#007b5e' />}>
                            <Onboarding />
                        </Suspense>
                    } />
<Route/>
return (
        isAuthenticated && callBackType != "impersonation" ? <Navigate to={navigateTo} /> : <Outlet />
    )
    

This is my code for Outlet and its also stop working on build but its working fine on dev server. can anyone please suggest me the solution that i am doing wrong ? it happens suddenly i didn't even changed anything

can anyone please suggest me the solution that i am doing wrong ? it happens suddenly i didn't even changed anything

@amentotech026 It's not necessarily your code, A recent change to the Rollup 4.16.1 breaks React Router on build. Just do what has been suggested above in your package.json file in the meantime while it gets sorted out.

As noted above, this is a bug introduced in rollup@4.16 which was released over the weekend, and vite uses a dependency of rollup@^4.13.0 so it can pick it up on fresh installs. It's being looked into by the rollup team (rollup/rollup#5443) and a PR is open with a fix (rollup/rollup#5482).

For now, you can install rollup@4.15.0 into your app's devDependencies or use the overrides field in package.json to pin to rollup@4.15.0 as a workaround.

is a very serious problem🥲

I had a same issue. it makes me to waste full day to fix. :( not good.
thank you, @brophdawg11 and others.

Rollup 4.16.2 is out with a fix that might address this. rollup/rollup#5482 (comment)

This should be resolved in rollup 4.16.2: https://github.com/rollup/rollup/releases/tag/v4.16.2

No more need for overrides for Vite projects, now that rollup is updated, this fixes it:

npm  upgrade rollup
// OR
pnpm upgrade rollup
// OR
yarn  upgrade rollup

Change the vite version to 4.4.1 build again and deploy. It should work

npm install rollup -D solved my issue. Thanks a lot!!