Dynamic Route Page Not Redirecting to 404 when using a dynamic route within another dynamic route
Answered
ASittingDuck posted this in #help-forum
I have one file that isn't redirecting to 404 when I am accessing a bad url
path template
example bad uri:
and another that is redirecting properly
path template
example bad uri:
path template
/admin/courses/[slug]/lessons/[lslug]
example bad uri:
/admin/courses/intro-into-react/lessons/bad-slug
import {PrismaClient} from '@prisma/client'
export const dynamicParams = false
export const dynamic = 'force-static'
export const revalidate = 60
const prisma = new PrismaClient()
export async function generateStaticParams() {
const lessons = await prisma.lesson.findMany()
return lessons.map((lesson) => ({
lslug: lesson.slug,
}))
}
const AdminLessonHome = async ({params}: { params: Promise<{ lslug: string }> }) => {
const lslug = (await params).lslug
const lesson = await prisma.lesson.findFirstOrThrow({
where: {slug: lslug},
})
// rest of the code
}
export default AdminLessonHome
and another that is redirecting properly
path template
/admin/courses/[slug]
example bad uri:
/admin/courses/bad-slug
import {PrismaClient} from '@prisma/client'
export const dynamicParams = false
export const dynamic = 'force-static'
export const revalidate = 60
const prisma = new PrismaClient()
export async function generateStaticParams() {
const courses = await prisma.course.findMany()
return courses.map((course) => ({
slug: course.slug
}))
}
const AdminCourseHome = async ({params}: { params: Promise<{ slug: string }> }) => {
const slug = (await params).slug
return <p>This is the main page for a course page on the admin side of the app. The current course id is {slug} </p>
}
export default AdminCourseHome
Answered by ASittingDuck
The issue is because you must define all the params in the dynamic route in the page.tsx for which you are defining the dynamic route. In this case you would say for example make it so that you have both the
slug
and lslug
definedexport async function generateStaticParams() {
const lessons = await prisma.lesson.findMany({
include: {
course: true
}
})
return lessons.flatMap((lesson) => ({
lslug: lesson.slug,
slug: lesson.course.slug
}))
}
2 Replies
The issue is indeed because of having a dynamic route within another dynamic route... because when I move it to
/admin/lesson/[lslug]
it works the way it shouldThe issue is because you must define all the params in the dynamic route in the page.tsx for which you are defining the dynamic route. In this case you would say for example make it so that you have both the
slug
and lslug
definedexport async function generateStaticParams() {
const lessons = await prisma.lesson.findMany({
include: {
course: true
}
})
return lessons.flatMap((lesson) => ({
lslug: lesson.slug,
slug: lesson.course.slug
}))
}
Answer