Next.js Discord

Discord Forum

Dynamic Route URL

Unanswered
Atlantic mackerel posted this in #help-forum
Open in Discord
Avatar
Atlantic mackerelOP
Hey guys,
I want to make Dynamic URL So I tried this


const validTypes = ['validType1', 'validType2']; 


const DynamicPage = ({ params }: { params: { type: string } }) => {

    return (
        <div>
            {params.type}
        </div>
    );
};

export default DynamicPage;

It work perfectly but I want to return page only these value
for example: [test,test2,test3,test4,test5]
So the path would be like
"localhost/contents/test, localhost/contents/test2, localhost/contents/tes3"
If the other paths return 404 page
Is there any other way to do this?

6 Replies

Avatar
New Guinea Singing Dog
I think you'll just have to check how many different routes are in it
Seems like Next JS only has catchall
So before you return the element you can check the length of the params array and if it is lonoger then 1 (e.g /content/test/x) return 404 or if you specifically want to match only the ones in validType you can also compare it
Avatar
To5y
add an if condition if the type is included the type arr bypassit else redirect it to 404 or throw an error
Avatar
New Guinea Singing Dog
Or you could move it to the middleware function to keep your code tidy
Avatar
Atlantic mackerelOP
Thank you everyone, I just did this

export default function Page({params}: { params: { type: string } }) {
    const routes = ["urlsssssssss"];
    if (!routes.includes(params.type)) {
        return null;
    }
    return (
        <div>

            <DragAndDrop/>
        </div>
    )
}