Next.js Discord

Discord Forum

Is there a way to detect that i am on not-found.tsx page?

Unanswered
Nile Crocodile posted this in #help-forum
Open in Discord
Nile CrocodileOP
I would need to change my page theme for not found page, for which i am using next-themes. IS there a way to detect page i am on not found page on client?

10 Replies

Largehead hairtail
if the browser shows you the not-found page, you are in there.
Nile CrocodileOP
@Largehead hairtail and i would detect it in code, how?
Largehead hairtail
may i know why you need to detect it?
Nile CrocodileOP
because i need to set different theme useing next-themes
'use client';

import { usePathname } from 'next/navigation';
import { ThemeProvider } from 'next-themes';
import { ThemeProviderProps } from 'next-themes/dist/types';

const getPageTheme = (pathname: string): ThemeProviderProps['forcedTheme'] => {
const neutral200Pages = ['about'];
const neutral100Pages = ['contact', thanks];

if (pathname === /news) {
return 'news';
}

if (pathname.startsWith(/news)) {
return 'news-article';
}

if (neutral200Pages.some((name) => pathname === /${name})) return 'neutral-200';
if (neutral100Pages.some((name) => pathname === /${name})) return 'neutral-100';

return 'neutral-25';
};

export function Providers({ children }: React.PropsWithChildren) {
const pathname = usePathname();
return (
#Unknown Channel
<ThemeProvider themes={["neutral-25", "neutral-100", "neutral-200", "news", "news-article", "neutral-900"]} forcedTheme={getPageTheme(pathname)}>
{children}
</ThemeProvider>
</>
)
}
so i would need if statement to return neutral-900 if i am on not-found page
Nile CrocodileOP
@Largehead hairtail does this help?
@Nile Crocodile Here is the only approach I can think of:
const pathname = usePathname();
const [responseStatus, setResponseStatus] = React.useState<number>();

React.useEffect(() => {
  const getResponseStatus = async () => {
    const response = await fetch(pathname);
    setResponseStatus(response.status);
  };

  getResponseStatus();
}, [pathname]);

Maybe it can be done on the middleware or server side. But on the client side, it's the only way I can think.
Nile CrocodileOP
@Nelson this would be even better if we could do it on server side. like if i could do it in root layout
Basically anything that would set class on html or body element would solve my problem