next.js: Add `app/` directory support for custom title in Error page
Describe the feature you’d like to request
I would like to have the possibility to control the page title, description etc. in the error and not-found page.
currently Its possible to get around not-found page by creating a conditional in metadata function for the not-found page but is still not nice.
Describe the solution you’d like
I would like not-found.js and error.js accept metadata and generateMetadata() similar to page.js and layout.js
// app/entity/[entityId]/not-found.js
export async function generateMetadata(props) {
return {
title: `entity ${props.params.entityId} not found`,
description: `There is no entity with id: ${props.params.entityId}`
}
}
export default function EntityNotFound() {
return <div>Sorry this Entity was not found</div>;
}
// app/error.js
export const metadata = {
title: "Error",
description: "ups something went wrong"
}
export default function Error() {
return <div>Sorry this Entity was not found</div>;
}
Describe alternatives you’ve considered
for not-found, maybe allow to pass the metadata object as an argument for the function
export default async function AnimalPage(props) {
const singleEntity = await getAnimalById(props.params.entityId);
if (!singleEntity) {
const metadata = {
title: `entity ${props.params.entityId} not found`,
description: `There is no entity with id: ${props.params.entityId}`
}
notFound(metadata);
}
return <>
... rest of the component
}
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 85
- Comments: 48 (17 by maintainers)
Would love this feature as well. Running a i18n site with this folder structure ->
[locale]/not-found.tsxI want to be able to get the locale param so we can fetch correct translations for not-found page.
Workaround (
<title>element)⚠️ Warning: As of
next@15.4.1, this is no longer working or needed fornot-found.tsxwith Next.js 15.4.1 -metadataandgenerateMetadata()appear to be working 🎉I guess for a static title, this hack can be used with the App Router (doesn’t result in a hydration error, interestingly enough):
Maybe this is what it will look like in the future once React Float more fully lands…
Or @gnoff @sebmarkbage should this already work now with the current state of React Float + Next.js? Was really surprised by lack of hydration error in both dev and production 🤔
Update Feb 2024: Maybe this is actually the new Document Metadata feature mentioned in the React Labs Feb 2024 “What We’ve Been Working On” blog post:
A related issue I don’t see mentioned here is that without metadata in error pages, the
viewportmeta tag is missing and mobile layouts are broken.Just hit an issue with this - we upgraded from Next 14 to Next 15 and the workarounds above no longer seem to work.
If metadata is specified in the
not-foundfile it briefly flashes in the browser title and then vanishes in dev mode.Tried calling
notFound()before the return in my routegenerateMetadatafunction but that leads to TS complaining about unreachable code. It also doesn’t seem to have any effect.Adding
<title>into the document works but doesn’t server render a title.At a loss as to what to do now.
Next.js 14.0.4 using App Router and
not-found.tsx:It works when I load the page, briefly, but the
page.tsxin the same folder overwrites the title immediately.Tested in developer-mode. Obviously, that should not happen.
Reading the docs: https://nextjs.org/docs/app/building-your-application/optimizing/metadata
…also doesn’t clear up the issue. Pages like
not-found.tsxaren’t part of the hierarchy, I suppose.I think this PR not full fixed, https://github.com/vercel/next.js/pull/52678
I see, dynamic routes with params makes sense. We’ll think of support for that case
@huozhi Any ETA on when
paramssupport will be added to thenot-found.jspage? I find it hard to believe that Next doesn’t support localized 404 pages out of the box, that seems like a pretty important feature.Did some research around metadata support for
not-foundanderrorconvention. It’s possible to support innot-foundwhen it’s server components as currently metadata is only available but forerrorit has to be client components then it’s hard to support it there as it’s a boundary. To support that it requires more changes in next.js to make them possible.@Super-Kenil Thanks for reply My goal was to keep at least default meta tags for error page in case if it is exposed to search engines. However, I noticed that error page has meta robots tag with “noindex” value, so the problem itself seems not actual from the beginning.
It is logical that page with error must not be indexed, but still it is strange that there is no way to handle error page’s meta tags on server side. All depends on project needs, it is not ok to just to remove such possibility at all.
Meanwhile, to solve the issue of page titles on 404-pages, assuming you have:
Then your not-found metadata currently cannot come from your not-found.tsx file, instead, you are to put it into your page.tsx file:
My issue with this is that I want the not-found page to be exclusively responsible for deciding how a 404-situation would look and feel. Now I need to make two files responsible for it, and I even need to do
pageExistsin both the page component and thegenerateMetadatafunction.But at least it works 😃
Should
generateMetadatawork innot-foundfile then? I’m testing inv13.4.19and it’s nothing.I’m also hoping this feature is added soon. We were able to do this in the
pagesdirectory using<Head>, so it’d be nice to have it with theappdirectory too 😄metadata+generateMetadata()available innot-found.tsxIt appears that
metadataandgenerateMetadata()are supported innext@15.4.1😍 🎉 🚀 probably even earlier, see belowSo one of the requests in this issue is finally closed! ✅
not-found.tsxReproduction: https://stackblitz.com/edit/github-z3vv6tsh?file=app%2Flayout.tsx,app%2Fnot-found.tsx,app%2Fpage.tsx
When did this land? I can see stable support as early as
next@15.1.7, maybe earlier…So a some point between Jan 2024 and Feb 2025 (
next@15.1.7), the feature has stabilized, possibly because of React or Next.js internal updates.At first, because of the 3x
<title>bug from Next.js 15.4.1, I thought this was maybe related to the Next.js 15.4 release: the Next.js 15.4 release notes added a similar feature toglobal-not-found.tsxby @huozhi in Notable changes:https://nextjs.org/blog/next-15-4#:~:text=[Feature] Support metadata in global-not-found (%2378961)
This
global-not-found.tsxis an experimental feature enabled usingexperimental.globalNotFoundand documented partly here:Oh too bad, so no way to generate dynamic titles / descriptions based on the requested content 🙁
Maybe there would still be some ways to support
generateMetadata()eg:notFound()used withingenerateMetadata()innot-found.tsx/error.tsx, throw an errorFacing the same issue and stumbled across this open issue
Here’s my workaround for the Next.js metadata issue in not-found.tsx (App Router): Instead of setting metadata directly in not-found.tsx, handle it in the dynamic route’s generateMetadata. This way, the metadata will be set correctly before notFound() is called.
This approach works because:
Hope this helps others who are facing the same issue! 🙌
Nope… at least for me, I’m testing 14.0 and my issue is still there. I have title and description defined statically in a parent layout file, and then in a child route an error file that simply tries to redefine them statically. When the error page loads, it shows for a fraction of second the correct metadata, and then it reverts back to the layout (parent) one. This happens in both dev and prod builds… I agree that Next has a ton of weird issues in apparently basic features, it makes me miss the good old client-server model…
Regarding the custom metadata for the not-found.js page, maybe I’ve found a workaround!
Currently, we are facing a problem where we throw a notFound() error when no page is found in our dynamic route. At that time, we don’t see the meta title and description of the not-found.js page. Instead, we see the meta data of the current page. I believe this is logical and not a bug in Next.js. In the case of a dynamic route, the meta data of the not-found.js page should also be dynamic, as it might be useful in some scenarios.
So, in the case of a dynamic route, we can set the meta data for the not-found.js page dynamically from page.js. It’s important to note that the generateMetadata function should not throw a notFound error. Instead, the page component should throw a notFound error. For example, you can see the screenshot below. I hope this solution works.
My folder structure:
No. I give up Next for now. I had a lot of problems and a lot of weird bugs.
@huozhi The not found page is refreshing every 3 seconds and we don’t have
<link rel="icon" href="/favicon.ico" type="image/x-icon" sizes="any">tag.@bacvietswiss that issue is fixed in #50044
Currently, I need to manually add
<meta name="viewport" content="width=device-width, initial-scale=1" ></meta>into the not found page in order to make it responsiveInteresting, seems like Shu was able to get a
document.titleon this example pageThis was part of this PR:
Not sure how this was achieved, I’ve asked over here:
Facing same issue, I’ve found a temporary solution. I duplicated title in exported metadata and in jsx. This works for me
Next.JS 15.3.2
I have the exact same problem. I feel stumped. I don’t know what to do.
Except for the header no Metadata is substituted at all. Including favicon and other tags.
error.tsx is client only page, for now, there’s no possible way to set metadata or even use generateMetaData to error.tsx page
But you can use a hack like this
Is it possible to set metadata for error.tsx file on SSR? I cannot find any information, generateMetadata function also does not work for client components (error.tsx forced to be client component).
I’m running into this issue now too, and it feels very unintuitive. I’d expect that when I call
notFound()in a page, it’s a signal to Next that this page should appear as nonexistent, and the entirety of mynot-found.tsxroute should render, metadata included.Having the underlying page title show up breaks that experience. Suppose I have a dynamic page that fetches some resource and checks to see if the current user should be able to view it. If they shouldn’t, then I want to tell them that the resource doesn’t exist by rendering our 404 page.
If the name of the resource shows up in the page title, it feels like a leaking of information that the current user shouldn’t have access to. Of course, I can do the additional check in the page’s
generateMetadatafunction as @marcelhageman suggests above, but that’s definitely a hacky workaround to this unexpected behaviour.Edit: I figured out that I can get the
not-found.tsxUI and metadata to render correctly by callingnotFound()from within mygenerateMetadatafunction.However this also feels like a hack and unexpected behaviour. Just wanted to mention this here in case others need a workaround while this issue is being addressed.
@itsjavi One possible workaround for that is similar to https://github.com/vercel/next.js/issues/48763#issuecomment-1623745516
…you can use a catch all route and put a
page.jsunder it, and then populategenerateMetadata.A possibly simpler interim solution to keep everything in
not-found.jsmay be to just update the title in the client side DOM e.g.useEffect(() => document.title = "Page Not Found")…as I suppose for error pages other meta tags are probably less important and don’t really need SSR support.
However, I agree with this issue that error pages should have their own
generateMetadatamethod, as it would be a cleaner and more consistent.I have something working for me. I determine if I am in a 404 state in generateMetadata for a route like. [blah]/page.tsx and return something like { title: ‘Not Found’ } in [blah]/not-found.tsx I just have the error markup. The meta data from page.tsx is present when I get my 404 hit I get the metadata set in page.tsx + <meta name="robots" content="noindex"/> added by the notFound() call. (notFound() is called in page.tsx’s component tree, not in generateMetadata of [blah]/page.tsx
Sure, I was thinking of something kind of similar to the one in the issue description: