Invalid Parameter Error in NextJS
In previous lessons, we returned
a 404 error
when the route for a given URL
was not found. However, in the case
of a dynamic route, a situation may arise
where the route exists,
but the parameter value is incorrect.
Let's look at an example.
Suppose we have a route like this:
/user/:id.
Let's also assume we have a users object:
let users = {
1: 'user1',
2: 'user2',
3: 'user3',
4: 'user4',
5: 'user5',
};
Suppose we want to display a user by their id:
export default function User({ params }) {
return <p>
{ users[params.id] }
</p>;
}
Obviously, the id in the URL cannot be
any value, but only one of the keys
in our object. An attempt to access
a non-existent address like
/user/6 should result
in an error being thrown. Let's fix
our component code and display
an error message:
export default function User({ params }) {
if (users[params.id]) {
return <p>
{ users[params.id] }
</p>;
} else {
return <p>
user not found
</p>;
}
}
However, this is not enough.
Because in this case, we are accessing
a non-existent page,
which means we should return an HTTP status of 404.
This is done using
a special function notFound,
built into NextJS.
Let's import this function:
import { notFound } from 'next/navigation';
And now we will call it when the parameter value is incorrect:
export default function User({ params }) {
if (users[params.id]) {
return <p>
{ users[params.id] }
</p>;
} else {
return notFound();
}
}
The full code of our component will look like this:
import { notFound } from 'next/navigation';
let users = {
1: 'user1',
2: 'user2',
3: 'user3',
4: 'user4',
5: 'user5',
};
export default function User({ params }) {
if (users[params.id]) {
return <p>
{ users[params.id] }
</p>;
} else {
return notFound();
}
}
Solve the described problem in your components.