Commit graph

58 commits

Author SHA1 Message Date
Jiachi Liu
f893c18528
Append sitemap extension and optimize imafe metadata static generation (#66477)
### What

Optimizing the static generation for dynamic metadata routes

If you're not using `generateSitemaps()` or `generateSitemaps()`, you
don't need to change any file conventions.
If you're using multi sitemap routes, make sure the returned `id`
properties from `generateSitemaps()` don't need to contain `.xml`, since
we'll always append one for you.

Analyzing the exports of metadata routes and determine if we need to
make them as dynamic routes.

### Why

Previously, users are struggling with the multi routes of sitemap or
images.
For sitemap, the `.xml` extension in url doesn't get appended
consistently to the multi sitemap route between dev and prod.
For image routes, the generated image routes are always dynamic routes
which cannot get static optimized.

The reason is that we need to always generate a catch-all route (such as
`/icon/[[...id]]` to handle both single route case (e.g. without
`generateImageMetadata`, representing url `/icon`) or multi route (e.g.
with `generateImageMetadata`, representing url `/icon/[id]`), only
catch-all routes can do it. This approach fail the static optimization
and make mapping url pretty difficult as parsing the file to check the
module exports has to be done before it.

#### Benifits

For image routes urls, this approach could help on static generation
such as single `/opengraph-image` route can be treated as static, and
then it can get static optimized if possible.

**Before**: `/opengraph-image/[[...id]]` cannot be optimized
**After**: single route `/opengraph-image` and multi-route
`/opengraph-image/[id]` are both possible to be statically optimized

For sitemap, since we removed appending `.xml` for dynamic routes, it’s
hard for users to have `/sitemap.xml` url with dynamic route convention
`sitemap.js` . But users desire smooth migration and flexibility.

**Before**: In v15 rc we removed the `.xml` appending that `sitemap.js`
will generate url `/sitemap` makes users hard to migrate, as users need
to re-submit the new sitemap url.
**After**: Now we'll consistently generate the `.xml`. Single route will
become `/sitemap.xml`, and multi route will become `/sitemap/[id].xml`.
It's still better than v15 as the urls generation is consistent, no
difference between dev and prod.

Here's the url generation comparsion

#### Before

All the routes are dynamic which cannot be optimized, we only had a
hacky optimization for prodution build multi-routes sitemap routes

| | only default export | `export generateImageMetadata()` | `export
generateSitemaps()` |
| -- | -- | -- | -- |
| opengraph-image.js | /opengraph-image/[[...id]] |
/opengraph-image[[...id]]/ | /opengraph-image/[[...id]] |
| sitemap.js | /sitemap/[[...id]] | /sitemap/[[...id]] | dev:
`/sitemap/[[...id]]` prod: `/sitemap/[id]` |

#### After

Most of the single route will are to get statically optimized now, and
the multi-routes sitemap are able to get SSG now

| | only default export | `export generateImageMetadata()` | `export
generateSitemaps()` |
| -- | -- | -- | -- |
| opengraph-image.js | /opengraph-image | /opengraph-image/[id] | - |
| sitemap.js | /sitemap.xml | - | /sitemap/[id].xml |

Next.js will have less overhead of mapping urls, we can easily multiply
the urls generation simply based on file conventions.

x-ref: feedback from #65507 
Closes #66232
2024-06-10 17:34:06 +02:00
Jiachi Liu
6cad9233fd
test: migrate dev error tests into separate sandbox test (#66666)
### What

Keep `test/e2e/app-dir/metadata-dynamic-routes/index.test.ts` with
successful build cases, move the dev error tests into separate test

### Why

x-ref:
https://github.com/vercel/next.js/actions/runs/9429301722/job/25975574075?pr=66286

Before the moving the tests, the error is flaky with turbopack since the
error will fail the hmr. Error observed with turbopack when seeing build
failed cases. So I moved the tests into the separate dev tests, running
inside sandboxes. Then each error test doesn't effect each other.

```
 ⨯ ./app/metadata-base/unset/icon--metadata.js:1:1
  Module not found: Can't resolve './icon.tsx'
  > 1 | import { generateImageMetadata } from "./icon.tsx"
      | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    2 | import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'
    3 |
    4 | const imageModule = { generateImageMetadata }

```
2024-06-10 11:57:33 +02:00
JJ Kasper
7e34b4cf98
Tweak flakey metadata error tests (#66060)
Seems we weren't grabbing the latest cli output inside of `check` so if
it wasn't ready by the time the first check successive checks wouldn't
have it either.

x-ref:
https://github.com/vercel/next.js/actions/runs/9182806177/job/25253023758
x-ref:
https://github.com/vercel/next.js/actions/runs/9182324607/job/25254072867
2024-05-21 21:53:16 -05:00
Jiachi Liu
09baadfd70
Remove auto appending xml extension to dynamic sitemap routes (#65507)
### What

Remove the auto appending `.xml` extension to the sitemap routes when
it's a dynamic route.


### Why

Previously we were adding `.xml` to `/[...paths/]sitemap` routes, but
the bad part is when you use it to generate multiple sitemaps with
`generateSitemaps` in format like `/[...paths/]sitemap.xml/[id]`, which
doesn't look good in url format and it can be inferred as xml with
content-type. Hence we don't need to add `.xml` in the url.

Before this change it could also result into the different url between
dev and prod:
dev: `/sitemap.xml/[id]`
prod: `/sitemap/[id].xml` 

Now it's going to be aligned as `/sitemap/[id]`. Users can add extension
flexiblely.

Closes NEXT-3357
2024-05-09 11:05:24 +02:00
Wyatt Johnson
c6320ed87a
Replace createNextDescribe with nextTestSetup (#64817)
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

I took some time and [wrote a
codemod](https://gist.github.com/wyattjoh/0d4464427506cb02062a4729ca906b62)
that replaces the old usage of the `createNextDescribe` with the new
`nextTestSetup`. You'll likely have to turn on hiding of whitespace in
order to review, but this should primarily introduce no changes to the
test structure other than using the new mechanism now.

Closes NEXT-3178
2024-04-25 12:06:12 -06:00
Juan Settecase
e4cd547a50
feat: add support for localizations in sitemap generator (#53765)
### What?

Following up with [this
suggestion](https://github.com/vercel/next.js/discussions/53540) I went
ahead and implemented the proposal for the Next.js team to merge it if
they agree.

Things to keep in mind:
- Google has [three different
ways](https://developers.google.com/search/docs/specialty/international/localized-versions#methods-for-indicating-your-alternate-pages)
to do this. The three of them are equivalent
- Google seems to be the only search engine supporting this approach.
The rest of them should ignore it

### Why?

This is supported by
[Google](https://developers.google.com/search/docs/specialty/international/localized-versions#example_2)
to better understand the site when the same page is available in
multiple languages.

### How?

- I added a new key to the `MetadataRoute.Sitemap` type called
`alternates` which accepts just one sub key `languages` similar to the
current one in the
[Metadata](https://nextjs.org/docs/app/api-reference/functions/generate-metadata#alternates)
object
- I updated the `resolveSitemap` method to process the new key and
generate the expected sitemap
- I updated the related tests and documentation to reflect the new
syntax

---------

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
2024-03-20 17:00:20 +00:00
Abhinay Pandey
f38dc18861
Fix: generateSitemaps in production giving 404 (#62212)
### What?
generateSitemaps function returns a 404 for /sitemap/[id].xml in
production

### Why?
While finding the correct sitemap partition from the array, we check the
param against the id. Which works in dev because id and param are both
without trailing .xml. But it fails in production as param has a
trailing .xml (/sitemap/[id] works in production because it falls back
to dynamic loading and param and id are both without .xml)

### How?
If we are in production environment, check the id with a trailing .xml
because that's whats returned from generateStaticParams, an array of
__metadata_id__ with trailing .xml

Fixes #61969

---------

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
2024-02-28 12:43:07 +01:00
Jiachi Liu
dc71a5721b
Fix trailing slash for canonical url (#62109)
### What

We should respect the `trailingSlash` config for metadata canonical url,
this PR is adding the handling for strip or keep the trailing slash for
canonical url. Passing down trailingSlash config to metadata resolving
to decide how we handle it.

### Why

The tricky one was `/` pathname, when visiting the origin directly, that
it will always have at least `/` in the URL instance. But for the
default `origin`, it shouldn't show the `/` if the `trailingSlash`
config is `false`. Also it should show trailing slash for all pathnames
if that config is enabled.

BTW there's a `__NEXT_TRAILING_SLASH` env but since we're using the
fixed nextjs runtime module, so this can't be dynamically replaced in
the metadata resolving modules. So we didn't use it

Fixes #54070 
Closes NEXT-2424
2024-02-15 18:57:15 +01:00
Jiachi Liu
5883a9a3a4
Fix sitemap generateSitemaps support for string id (#61088)
### What

Fixes the string id that broken when sitemap is optimized to static
route.

### Why

When sitemap is optimized to static route in production, the route
argument is changed from `[[...__metadata_id__]]` to
`[__metadata_id__]`, so the type of it is also changed from array to
string that should reflect in the loader code.

Fixes #60894 
Closes NEXT-2154
2024-01-24 16:52:52 +01:00
Jiachi Liu
3db878629e
Fix dynamic sitemap detection (#60356)
### What

Fix bad detection of dynamic route of sitemap metadata route, the swc
AST check should process when the text are detected. But prevuious if
there's text with `generateSitemap` such as comment but not the actual
export it will fail.

### How
Add both checks on metadata loader side and detection helper side

* Only call `generateSitemaps` helper when the export existed
* Fix the helper detection logic (major part of this PR)

Fixes #59698
Closes #60344
Closes NEXT-2007
2024-01-08 14:11:00 +01:00
Jiachi Liu
14052c052e
Upgrade og dependencies (#59541)
Upgrade `@vercel/og` to 0.6.1

Closes NEXT-1857
2023-12-21 14:50:57 +01:00
Jiachi Liu
6b6bfcd387
Polish logging segments of page route (#57834)
Reduce the confusiong of the the logging of pages, make it easier to understand

* Removing the trailing `/page`, `/route` suffix 
* Removing the internal segment like `[[...__metadata__]]` 



#### After

```
 ○ Compiling / ...
 ○ Compiling /dynamic/[slug]/icon ...
```
#### Before
```
 ○ Compiling /page ...
 ○ Compiling /(group)/dynamic/[slug]/icon-ahg52g/[[...__metadata_id__]]/route ...
```

Closes NEXT-1701
2023-11-01 16:34:52 +00:00
OJ Kwon
cce9f0d34f
fix(metadata): align metadata suffix hash between turbopack (#57544)
### What?

Wraps up metadata-dynamic-routes tests fixes for the turbopack. There is 1 remaining failing test due to lacks of supporting `import.meta.url` which need to be addressed separately.

I spent amount of time why turbopack cannot find the route for the dynamic metadata for a certain route. In the end, found there are mismatching expectations for the route due to different hash for the certain route. We do use the same djb2 hash between next.js and turbopack both, so it was quite confusing why we don't get deterministic hash.

After trying some experiments, found out root cause was how 2 different runtimes handle overflow for given type of numbers. In rust + turbpack we use u32 and do 32-bit hash calculation for given string, while in js we implicitly used number type as is, in result overflow occurs with default 53-bit float. 

Originally I tried to adjust hash in turbopack side to preserve js hash as-is, but so far I found it was non trivial to do so as rust there's no out of the box types we can coerce to the js number type. In result, unlike other fixes in turbopack this PR changes how js hash is being generated. I hope this woulndn't be a breaking changes; expect so since this is a metadata specific hash that we do not have written spec for it.

Closes WEB-1890
2023-10-30 19:56:55 +00:00
Jiachi Liu
3553c6516d
Improve error for missing default export in dynamic metadata routes (#57711)
Displaying hints of "missing default export" if you didn't properly export the `default` handler for og image 

```
   ▲ Next.js 14.0.1-canary.2
   - Local:        http://localhost:3000

 ✓ Ready in 1089ms
 ✓ Compiled /opengraph-image/[[...__metadata_id__]]/route in 211ms (44 modules)
 ⨯ Error: Default export is missing in "/Users/huozhi/workspace/next.js/test/e2e/app-dir/metadata-dynam
ic-routes/app/opengraph-image.tsx"
    at eval (webpack:///app/opengraph-image.tsx?3407:11:1)
    at (app-metadata-route)/../../../../packages/next/dist/build/webpack/loaders/next-metadata-route-lo
ader.js?page=%2Fopengraph-image%2F%5B%5B...__metadata_id__%5D%5D%2Froute&isDynamic=1!./app/opengraph-im
age.tsx?__next_metadata_route__ (/Users/huozhi/workspace/next.js/test/e2e/app-dir/metadata-dynamic-rout
es/.next/server/app/opengraph-image/[[...__metadata_id__]]/route.js:362:1)
    at __webpack_require__ (/Users/huozhi/workspace/next.js/test/e2e/app-dir/metadata-dynamic-routes/.n
ext/server/webpack-runtime.js:33:42)
```
2023-10-30 16:36:24 +00:00
Balázs Orbán
33db463fe4
chore: upgrade jest (#56909)
### What?

Upgrade jest to its latest version

### Why?

#56899 fails because historically Jest stripped the globals in Node.js, but 28+ isn't doing that anymore. If we upgrade, we don't have to keep track of Node.js globals and when they are added. This will be useful in removing even more polyfills for things that are natively shipped in Node.js now.

### How?

Jest 29 introduced a change to the snapshot format: https://jestjs.io/blog/2022/08/25/jest-29

First, I tried setting the old compat option to not require updating snapshots, but some tests were still failing: https://dev.azure.com/nextjs/next.js/_build/results?buildId=70633&view=logs&j=8af7cf9c-43a1-584d-6f5c-57bad8880974&t=7ae70e63-3625-50f4-6764-5b3e72b4bd7a&l=273 So going through the pain now instead.
2023-10-19 17:38:24 +00:00
Jiachi Liu
a3e56c9c1e
Move ImageResponse to next/og (#56662)
### Story

Since we introduced `ImageResponse` into `next/server` export, there're a few libraries relying on `next/server` that accidentally ended up with bundling og image into the bundle. As og package is quite large that could easily raise the size concern for middleware, edge runtime routes.

### Struggles
 We've done optimizations. The tree-shaking strategies are tricky, we tried modularize imports and also optimize cjs require/exports to make sure you're not including og package into bundle if it's not being used. However, it's still not 100% can handle all the bundle optimization cases, such as `import {..} from "next/server.js"` could also ended up with the cjs bundle that failed the tree-shaking.

### Move on
So we decide to move og `ImageResponse` into a separate export `next/og`

Closes NEXT-1660
2023-10-19 14:26:48 +00:00
Quentin
abe8b1e0a8
Improve performance of String.prototype.split uses (#56746)
This PR adds the optional `limit` parameter on String.prototype.split uses.

> If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#syntax)

While the performance gain may not be significant for small texts, it can be huge for large ones.

I made a benchmark on the following repository : https://github.com/Yovach/benchmark-nodejs

On my machine, I get the following results:
`node index.js`
> normal 1: 570.092ms
> normal 50: 2.284s
> normal 100: 3.543s

`node index-optimized.js`
> optmized 1: 644.301ms
> optmized 50: 929.39ms
> optmized 100: 1.020s

The "benchmarks" numbers are : 
- "lorem-1" file contains 1 paragraph of "lorem ipsum"
- "lorem-50" file contains 50 paragraphes of "lorem ipsum"
- "lorem-100" file contains 100 paragraphes of "lorem ipsum"
2023-10-19 00:25:15 +00:00
Jiachi Liu
4a6319cd86
Respect the original exported route segment config for sitemap (#56007)
Re-export the original route segment config in metadata routes loader, so they can be picked up by app route module wrapper

Closes #54057
Closes NEXT-1645
2023-09-26 17:04:58 +00:00
Jiachi Liu
063154918c
Fix react packages are not bundled for metadata routes (#55579)
`isAppLayer` condition was missing `app-metadata-route` layer, made it
as a util now like other webpack layer utils, add metadata route layer
to the group. Then `React.cache` can be available there.

Also update regex to be compatible across platform

Fixes #55561 
Closes NEXT-1635
2023-09-19 15:45:59 +02:00
Jiachi Liu
f2f1c251bf
Fix duplicated dynamic metadata routes in dev mode (#55026)
In dev mode, we're using a catch-all route for dynamic metadata routes, e.g. page path `/twitter-image` would become `/twitter-image/[[...metadata_id...]]/route` as a dynamic custom app route.

But we're missing to convert it in filesystem scanning for routing purpose, adding the metadata related normalizing logic for app page to align with other places.
2023-09-06 00:21:06 +00:00
Max Leiter
4c3b7f9b7a
Export RedirectType from next/navigation (#54729)
A continuation of #51864 with RedirectType used in an e2e test and some
ts-ignores removed from the codebase. Happy to split it into two PRs but
I left comments in the two consequential files

---------
2023-08-29 11:05:44 -07:00
Jiachi Liu
85606472e4
Add test for using custom font in metadata image routes (#54274)
In the past few rounds of improving metadata image routes bundling, we have improved the bundling strategy and also updated [the usage tutorial of using custom fonts in og image routes](https://vercel.com/docs/functions/edge-functions/og-image-generation/og-image-examples) which should load the font in the image route handler.

Adding some tests to ensure custom fonts are working with metadata

Closes #48081
2023-08-19 14:29:18 +00:00
Luud Janssen
5fe332186e
Add changeFrequency and priority attributes to sitemaps (#48484)
Closes #48479. 

Couldn't find the source for the Next.js beta docs, so I didn't add documentation.

Co-authored-by: Jiachi Liu <4800338+huozhi@users.noreply.github.com>
2023-08-09 20:36:22 +00:00
Jiachi Liu
632a582807
Fix metadata layer webpack rule for server-only (#52403)
After we separating the metadata routes to a separate layer, we didn't apply the webpack alias rules properly to it as it's should still be treated as pure "server" side

This PR fixes the aliasing for that new metadata layer and make it working properly with "server-only"

Fixes #52390
2023-07-09 18:23:51 +00:00
Tim Neutkens
e10431612d
Remove test skip (#51988)
Re-enables the test disabled in #51879 as it was fixed in #51973
2023-06-29 20:23:55 +00:00
Tim Neutkens
ed280d2c46
Add shared input filesystem (#51879)
## What?

Currently we use 3 separate webpack compilers:

- server
- client
- edge

All of these were creating their own input filesystem (which is used to
read file, stat, etc.). Changing them to share a single inputFileSystem
allows the `cachedFileSystem` to be reused better, as `stat` and
`readFile` can be cached across the 3 compilers.

For the page on vercel.com we've been testing this shaves off 300-400ms
on a cold compile (no cache, deleted `.next`).

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------

Co-authored-by: Shu Ding <g@shud.in>
2023-06-29 15:49:05 +02:00
Tim Neutkens
3773c5be8c
Ensure metadata test is not affected by other tests (#51973)
Turn out the `should error when id is missing in generateSitemaps` test
was passing because of this test passing: `should error when id is
missing in generateImageMetadata`

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
2023-06-29 15:10:19 +02:00
Jiachi Liu
db4b9858ca
Add esm entry for next/server and alias @vercel/og (#51651)
The next-metadata-route-loader emitted content with `"next/server"` is still using cjs version which is not get tree-shaked on edge runtime, This PR adds a new esm entry for it and mapped it that on edge runtime so unused exports can be tree-shaked. This case happened when users are using ImageResponse from `"@vercel/og"` instead of `"next/server"`.

2nd change is adding another alias to map `@vercel/og` package to vendored og package inside next.js, this way we could merge the two package instead of bundled both of them


Fixes: NEXT-1303

changed `require.reoslve("next/dist/xxx")` to `${NEXT_PROJECT_ROOT}/xxx}` to avoid to be traced by nft.
2023-06-22 21:34:12 +00:00
Tim Neutkens
25a9547cad
Remove experimental config from create-next-app (#49241)
## What?

Removes `experimental.appDir` this was leftover from when I flipped the
switch.

Kept the config file as in the future we might add future flags and
such. It also helps that it has the types comment included so you always
get types.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------

Co-authored-by: JJ Kasper <jj@jjsweb.site>
2023-05-05 00:22:28 -07:00
Jiachi Liu
c09b0a0890
Static generate dynamic sitemaps (#49114)
Follow up of #48867 

- Statically optimize dynamic generated sitemap routes
- Previously the generated sitemap urls looks bit off
(`/route/sitemap.xml/[id]`), we polish it into `/route/sitemap/[id].xml`
in this PR
2023-05-03 12:11:57 +02:00
Jiachi Liu
9102771c65
Optimize non-dynamic metadata routes to static in production build (#49109)
* For sitemap if they're not using dynamic routes generation `generateSitemaps`, should optimize them as static sitemap
* For icons and social images, if they're not using `generateImageMetadata`, should optimize them as static path

Closes NEXT-1071
Fixes #48991
2023-05-02 21:36:44 +00:00
Jiachi Liu
a141366ff6
Error for missing dynamic generated id and refactor metadata image url (#48953)
### What?

In #48928 we decided to error for the missing `id` from `generateImageMetadata` and `generateSitemaps` for better dev DX. This PR also refactors the metadata image urls generation that assumbling the utils together
2023-04-28 14:06:07 +00:00
Jiachi Liu
44dc4efad2
Fix dynamic routes for generateImageMetadata (#48928)
* Fix the `generateImageMetadata` for non dynamic routes and related
`param` matching (Found during development)
* Fix dynamic routes with number suffix `(\d)` (Fixes #48689)
2023-04-28 12:27:21 +02:00
Jiachi Liu
98e0c4a51c
External vercel og for nodejs runtime (#48844)
### Why

Default font file of `@vercel/og` is not loaded, because the og package is bundled by webpack and we should external it so that `fs.readFileSync` is bundled and manged that can't be traced by nft.


### How
This PR externals `@vercel/og` so that they don't need to be bundled and files can be properly traced

Closes NEXT-1047
Fixes #48704
2023-04-26 23:36:42 +00:00
Jiachi Liu
a4d63092e8
Support generate dynamic sitemaps for dynamic routes (#48867)
### What

For dynamic routes you might have different sitemap for different params

* Unloack using `sitemap.[ext]` in your app everywhere
* Support `generateSitemaps()` to create multiple sitemaps at the same time

### How

* Change the metadata regex to allow use sitemap in every routes
* Similar approach to `generateImageMetadata`, we make `sitemap.js` under dynamic routes to a catch all routes, and it can have multiple routes

Closes NEXT-1054
2023-04-26 20:41:37 +00:00
Jiachi Liu
0a04ab65b6
Fallback to deployment vercel url if metadataBase is not set on prod (#48570)
x-ref:
https://github.com/vercel/next.js/pull/48556#discussion_r1171163992

For production deployment, we still fallback to deployment URL if
`metadataBase` is not set.
2023-04-19 13:45:51 +00:00
Jiachi Liu
6f30c911d6
Prefer to use deployment url for metadata routes on production (#48556)
Use should only need to configure one `metadataBase` as fixed domain or
url but metadata image routes can still work properly with `VERCEL_URL`
in preview deployments

If you configured `new URL('https://mydomain.com')`, it will work for
canonical url all the time since it's for SEO.
For preview deployments metadata image routes will work with deployment
url as they're always bound with deployment.
For production deployments metadata images routes can be alias to the
configured `metadataBase` as they could be the expected exposed domain

Follow up for #47910

link NEXT-887
2023-04-19 10:26:08 +00:00
Jiachi Liu
7aba242b75
feat: generate image metadata (#48362)
### What?

* Support `generateMetadata(props)` to dynamically generate multiple
metadata images at the same time

```js
// /app/opengraph-image.tsx
import { ImageResponse } from 'next/server';

export async function generateImageMetadata({params}) {
  const images = await ...;
  return images.map((img, idx) => ({
    size: { width: 1200, height: 600 },
    alt: img.text,
    contentType: 'image/png',
    id: idx,
  }));
}

export default async function ({params, id}) {
  const text = await getTextFor(id);
  return new ImageResponse(
    (
      <div
        style={{...}}>
        {text}
      </div>),
    { width: 1200, height: 600 },
  );
}
```

### How?

Use `<metadata image>/[[...__metadata_id__]]/route.js` to catch all
metadata images id, and then use this `params.__metadata_id__` as id
argument for dynamic generate image.

If there's param, then we create `<metadata image>/<id>`, if there's
only 1 static image without dynamic `generateImageMetadata` then we keep
use `<metadata image>`

Closes NEXT-896
2023-04-14 20:52:31 +00:00
Jiachi Liu
d569b83819
Auto collect custom manifest into metadata (#48310)
when custom manifest is found, collect it as metadata and insert into
head

Closes NEXT-988
2023-04-13 00:47:19 +00:00
Yamagishi Kazutoshi
958150d15b
Add suffix to static metadata images (#48202)
### What?

The change in #47985 breaks the URLs of static image files like
`/(group)/opengraph-image.png` to `/opengraph-image.png-012345`.
References from `/` are also broken.

### Why?

This is because only `opengraph-image.ts` and `opengraph-image.tsx` are
considered.

### How?

In this Pull Request, we are trying to solve the problem by including
similar support for `opengraph-image.png` and `opengraph-image.jpeg`.

---------

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
2023-04-12 14:30:31 +00:00
Jiachi Liu
71a29a17b8
Support og image with edge (#48086)
Fixing edge runtime doesn't work with exports from dynamic metaddata
image routes. If there's a match, don't do extra matching.

Fixes NEXT-866
2023-04-07 16:27:32 -07:00
Jiachi Liu
1e81af047d
Change metadata routes suffix to number and chars (#48026)
Follow up of #47985 

Change `-\d{6}` to `-[a-z0-9]{6}` which reduces the chance of hash
collision
2023-04-06 16:38:02 -07:00
Jiachi Liu
c0751e8c81
Create unique route path for og under group routes (#47985)
### What

When using dynamic metadata image rouets (such as `opengraph-image.js`)
under group routes, the generated urls were still normalized. In this
case it might have conflicts with those ones not under group routes. For
instance `app/(post)/opengraph-image.js` could have same url with
`/app/opengraph-image.js`. In reality we want them to be different
route, unlike layout or pages.

### How

So when we found `()` or `@` signs from the metadata image urls, we'll
generate a unqiue suffix (`-\d{6}`) and append to the generated url. So
they can be isolated from the ones are not under special convention
routes.

Closes NEXT-937
2023-04-05 22:40:17 +00:00
Jiachi Liu
68f328f920
Fix: fill route params for dynamic route metadata images url (#47829)
Should fill dynamic routes url with params when generate the metadata
image urls.

For `/(group)`, we need to normalize the path first;
For dynamic routes `/[slug]`, we need to fill the params.

Change the image module from `() => image` to `(prop) => image(proop)`
so we can fill the runtime `params` into url

Closes NEXT-932

---------
2023-04-02 23:42:33 -07:00
Jiachi Liu
2a5c558963
Skip favicon.js for metadata (#47790)
For backward compatibility, we only handle `favicon.ico` file to
generate `/favicon.ico` route and link tag. If you want to use other
extension such as `png`, use `icon(\d)?.[ext]`
2023-04-02 01:35:24 +02:00
Jiachi Liu
d71cbe9116
Vendor @vercel/og and expose ImageResponse (#47715)
- Reverts #47711 
- Disable image response for turbopack
2023-03-31 02:29:10 +00:00
Jiachi Liu
6dbb6318a1
Provide default metadataBase for local and vercel deployment (#47568)
### What?

- Provide a default `metadataBase` 
- Always resolve urls that could be resolved as absolute with
`metadataBase`, e.g. tw/og urls, canonical urls
- Give a warning in dev mode if user doesn't provide one in dev
- Error if you don't have it but it's required in production

On production it will leverage `VERCEL_URL` if users expose it to the
deployment

### Why?

OG image urls are required to be absolute urls instead of relative urls.
For metadata image conventions we let users don't have to provide
`metadataBase` explicitly when they expect it should be the origin of
their next app.

### How?

Closes NEXT-887

---------
2023-03-30 16:27:24 -07:00
Jiachi Liu
35cf930572
Update MetadataRoute to namespace (#47674)
### What?

Followup for #47630 , use ts namespace to group MetadataRoute.

`MetadataRoute['xxx']` -> `MetadataRoute.xxx`

### Why?

namespace is convenient to write for these grouped types such as
`MetadataRoute.Robots`. And `MetadataRoute` itself is not actually a
type. So it can be conveniently typed by ts users.

### How?

Closes NEXT-912

---------
2023-03-30 15:27:44 -07:00
JJ Kasper
2ac022391c
Revert "Vendor @vercel/og and expose ImageResponse (#47657" (#47711)
Reverts vercel/next.js#47657
2023-03-30 12:24:02 -07:00
Jiachi Liu
99cdb36663
Vendor @vercel/og and expose ImageResponse (#47657
### What?

This PR vendors @vercel/og and export `ImageResponse` from
`next/server`. When you render a opengraph image the below code snippets
will be legit:

```tsx
import { ImageResponse } from 'next/server'

export default function og() {
  return new ImageResponse(<div style={{ width: '100%', height: '100%' }}>hello</div>)
}
```

### Why?

To make development more easier, user can directly use `@vercel/og`
Image Response with nextjs instead of install it and use it. This makes
building metadata icons, og or twitter images more convenient.

### How?

Closes NEXT-899
2023-03-30 13:06:30 +02:00