How do I redirect all missed routes to the home page?
Unanswered
Siamese Crocodile posted this in #help-forum
Siamese CrocodileOP
I need to redirect from 404 to /
for example if someone visits example.com/horse I need it to redirect to example.com since /horse doesn't exist.
Using next.js 14 App Directory.
for example if someone visits example.com/horse I need it to redirect to example.com since /horse doesn't exist.
Using next.js 14 App Directory.
7 Replies
Try this:
In
In
pages/404.js:import { useEffect } from "react"
import { useRouter } from "next/router"
export default function Custom404() {
const router = useRouter()
useEffect(() => {
router.replace("/")
})
return null
}Oh sorry, you're using app directory
Then it would be
app/not-found.tsxAlso, I forgot the
'use client';@Siamese Crocodile I need to redirect from 404 to /
for example if someone visits example.com/horse I need it to redirect to example.com since /horse doesn't exist.
Using next.js 14 App Directory.
// app/not-found.tsx
import { redirect } from "next/navigation";
export default function NotFound() {
redirect("/");
}untested but should work
Forest bachac
For app router: https://nextjs.org/docs/app/api-reference/file-conventions/not-found " In addition to catching expected notFound() errors, the root app/not-found.js file also handles any unmatched URLs for your whole application. This means users that visit a URL that is not handled by your app will be shown the UI exported by the app/not-found.js file."
@joulev tsx
// app/not-found.tsx
import { redirect } from "next/navigation";
export default function NotFound() {
redirect("/");
}
untested but should work
Yeah, it doesnt need to be client component, its already a server component by default. So I think your solution looks cleaner