Commit 6ac867df authored by nutlope's avatar nutlope

Merge branch 'canary' into improve-data-fetching

parents 81bb40fe f5163046
# Contributing to Next.js
Read about our [Commitment to Open Source](https://vercel.com/oss). To
contribute to [our examples](examples), please see **[Adding
examples](#adding-examples)** below.
[Watch the 40-minute walkthrough video on how to contribute to Next.js.](https://www.youtube.com/watch?v=cuoNzXFLitc)
Before jumping into a PR be sure to search [existing PRs](https://github.com/vercel/next.js/pulls) or [issues](https://github.com/vercel/next.js/issues) for an open or closed item that relates to your submission.
---
- Read about our [Commitment to Open Source](https://vercel.com/oss).
- To contribute to [our examples](examples), please see [Adding examples](#adding-examples) below.
- Before jumping into a PR be sure to search [existing PRs](https://github.com/vercel/next.js/pulls) or [issues](https://github.com/vercel/next.js/issues) for an open or closed item that relates to your submission.
## Developing
......
......@@ -48,7 +48,7 @@ Or add a `className` to the `body` tag:
> **Note:** This is advanced and only needed for libraries like CSS-in-JS to support server-side rendering. This is not needed for built-in `styled-jsx` support.
To prepare for [React 18](/docs/advanced-features/react-18.md), we recommend avoiding customizing `getInitiaProps` and `renderPage`, if possible.
To prepare for [React 18](/docs/advanced-features/react-18.md), we recommend avoiding customizing `getInitialProps` and `renderPage`, if possible.
The `ctx` object shown below is equivalent to the one received in [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md#context-object), with the addition of `renderPage`.
......
......@@ -155,7 +155,22 @@ The above generates the following `HTML`:
</ul>
```
When you want to style your own elements to give a custom feel to your website or application, you can pass in shortcodes. These are your own custom components that map to `HTML` elements. To do this you use the `MDXProvider` and pass a components object as a prop. Each object key in the components object maps to a `HTML` element name. You also need to specify `providerImportSource: "@mdx-js/react"` in `next.config.js`.
When you want to style your own elements to give a custom feel to your website or application, you can pass in shortcodes. These are your own custom components that map to `HTML` elements. To do this you use the `MDXProvider` and pass a components object as a prop. Each object key in the components object maps to a `HTML` element name.
To enable you need to specify `providerImportSource: "@mdx-js/react"` in `next.config.js`.
```js
// next.config.js
const withMDX = require('@next/mdx')({
// ...
options: {
providerImportSource: '@mdx-js/react',
},
})
```
Then setup the provider in your page
```jsx
// pages/index.js
......@@ -186,6 +201,8 @@ export default function Post(props) {
}
```
If you use it across the site you may want to add the provider to `_app.js` so all MDX pages pick up the custom element config.
## Helpful Links
- [MDX](https://mdxjs.com)
......
......@@ -252,19 +252,23 @@ const Example = () => (
import Image from 'next/image'
import React from 'react'
const Container = React.forwardRef((props, ref) =>
<div ref={ref} style={{ overflowX: 'scroll', width: '500px' }}>
{props.children}
</div>
const Container = React.forwardRef((props, ref) => {
return (
<div ref={ref} style={{ overflowX: 'scroll', width: '500px' }}>
{props.children}
</div>
)
})
const Example = () => {
const lazyRoot = React.useRef(null)
return (<Container ref={lazyRoot}>
<Image lazyRoot={lazyRoot} src="/one.jpg" width="500" height="500" />
<Image lazyRoot={lazyRoot} src="/two.jpg" width="500" height="500" />
</Container>)
return (
<Container ref={lazyRoot}>
<Image lazyRoot={lazyRoot} src="/one.jpg" width="500" height="500" />
<Image lazyRoot={lazyRoot} src="/two.jpg" width="500" height="500" />
</Container>
)
}
```
......
......@@ -97,7 +97,35 @@ As `getStaticProps` runs only on the server-side, it will never run on the clien
This means that instead of fetching an **API route** from `getStaticProps` (that itself fetches data from an external source), you can write the server-side code directly in `getStaticProps`.
Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getStaticProps`. This produces an additional call, reducing performance. Instead, the logic for fetching the data from the CMS can be moved to `getStaticProps`.
Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getStaticProps`. This produces an additional call, reducing performance. Instead, the logic for fetching the data from the CMS can be shared by using a `lib/` directory. Then it can be shared with `getStaticProps`.
```jsx
// lib/fetch-posts.js
// The following function is shared
// with getStaticProps and API routes
// from a `lib/` directory
export async function loadPosts() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts/')
const data = await res.json()
return data
}
// pages/blog.js
import { loadPosts } from '../lib/load-posts'
// This function runs only on the server side
export async function getStaticProps() {
// Instead of fetching your `/api` route you can call the same
// function directly in `getStaticProps`
const posts = await loadPosts()
// Props returned will be passed to the page component
return { props: { posts } }
}
```
Alternatively, if you are **not** using API routes to fetch data, then the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API _can_ be used directly in `getStaticProps` to fetch data.
......
......@@ -152,26 +152,26 @@ export default async () => {
## Environment Variable Load Order
Depending on the environment (as set by `NODE_ENV`), variables are loaded from the following sources in order from top-to-bottom. In all environments existing env is not overridden by following sources.
Depending on the environment (as set by `NODE_ENV`), Environment Variables are loaded from the following sources in top-to-bottom order. In all environments, the existing `env` is not overridden by following sources:
`NODE_ENV=production`
- `.env.production.local`
- `.env.local`
- `.env.production`
- `.env`
1. `.env.production.local`
1. `.env.local`
1. `.env.production`
1. `.env`
`NODE_ENV=development`
- `.env.development.local`
- `.env.local`
- `.env.development`
- `.env`
1. `.env.development.local`
1. `.env.local`
1. `.env.development`
1. `.env`
`NODE_ENV=test`
- `.env.test.local`
- `.env.test`
- `.env`
1. `.env.test.local`
1. `.env.test`
1. `.env`
_(note: `.env.local` is not loaded when `NODE_ENV=test`)_
> **Note:** `.env.local` is not loaded when `NODE_ENV=test`.
......@@ -6,7 +6,7 @@ description: Get started with Next.js in the official documentation, and learn m
Welcome to the Next.js documentation!
If you're new to Next.js we recommend that you start with the [learn course](https://nextjs.org/learn/basics/create-nextjs-app).
If you're new to Next.js, we recommend starting with the [learn course](https://nextjs.org/learn/basics/create-nextjs-app).
The interactive course with quizzes will guide you through everything you need to know to use Next.js.
......@@ -17,7 +17,7 @@ If you have questions about anything related to Next.js, you're always welcome t
- [Node.js 12.22.0](https://nodejs.org/) or later
- MacOS, Windows (including WSL), and Linux are supported
## Setup
## Automatic Setup
We recommend creating a new Next.js app using `create-next-app`, which sets up everything automatically for you. To create a project, run:
......@@ -89,12 +89,12 @@ export default HomePage
So far, we get:
- Automatic compilation and bundling (with webpack and babel)
- Automatic compilation and [bundling](/docs/advanced-features/compiler.md)
- [React Fast Refresh](https://nextjs.org/blog/next-9-4#fast-refresh)
- [Static generation and server-side rendering](/docs/basic-features/data-fetching/overview.md) of [`./pages/`](/docs/basic-features/pages.md)
- [Static file serving](/docs/basic-features/static-file-serving.md). `./public/` is mapped to `/`
In addition, any Next.js application is ready for production from the start, read more in our [Deployment documentation](/docs/deployment.md).
In addition, any Next.js application is ready for production from the start. Read more in our [Deployment documentation](/docs/deployment.md).
## Related
......@@ -110,7 +110,7 @@ For more information on what to do next, we recommend the following sections:
<div class="card">
<a href="/docs/basic-features/built-in-css-support.md">
<b>CSS Support:</b>
<small>Use the built-in CSS support to add custom styles to your app.</small>
<small>Built-in CSS support to add custom styles to your app.</small>
</a>
</div>
......
......@@ -33,10 +33,10 @@ The front-end looks like this:
The HTML `<form>` tag acts as a container for different `<input>` elements like `text` field and submit `button`. Let's study each of these elements:
- `action`: An attribute that specifies where the form data is sent when the form is submitted. It's generally a URL (an absolute URL or a relative URL).
- `method`: Specifies the HTTP method, i.e., `GET` or `POST` used to send data while submitting the form.
- `<label>`: An element that defines the label for other form elements. Label aids accessibility, especially for screen readers.
- `method`: Specifies the [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods), i.e., `GET` or `POST` used to send data while submitting the form.
- `<label>`: An element that defines the label for other form elements. Labels aid accessibility, especially for screen readers.
- `<input>`: The form element that is widely used to structure the form fields. It depends significantly on the value of the `type` attribute. Input types can be `text`, `checkbox`, `email`, `radio`, and more.
- `<button>`: It represents a clickable button that's used to submit the form data.
- `<button>`: Represents a clickable button that's used to submit the form data.
### Form Validation
......@@ -55,11 +55,11 @@ Client-side validation is further categorized as:
### Built-in Form Validation Using `required`, `type`, `minLength`, `maxLength`
- `required`: Specifies which fields must be filled before submitting the form.
- `type`: Tells whether the data should be a number, email id, text string, etc.
- `minLength`: Decides the minimum length for the text data string.
- `maxLength`: Decides the maximum length for the text data string.
- `type`: Specifies the data's type (i.e a number, email address, string, etc).
- `minLength`: Specifies minimum length for the text data string.
- `maxLength`: Specifies maximum length for the text data string.
The following example shows using these attributes:
So, a form using this attributes may look like:
```html
<!-- HTML Form with Built-in Validation -->
......@@ -85,7 +85,7 @@ With these validation checks in place, when a user tries to submit an empty fiel
### JavaScript-based Form Validation
Form Validation is important to ensure that a user has submitted appropriate data. JavaScript offers an additional level of validation along with HTML native form attributes on the client side. Developers generally prefer validating form data through JavaScript because its data processing is faster when compared to server-side validation.
Form Validation is important to ensure that a user has submitted the correct data, in a correct format. JavaScript offers an additional level of validation along with HTML native form attributes on the client side. Developers generally prefer validating form data through JavaScript because its data processing is faster when compared to server-side validation, however front-end validation may be less secure in some scenarios as a malicious user could always send malformed data to your server.
The following example shows using JavaScript to validate a form:
......@@ -143,7 +143,7 @@ The below example shows using the `pattern` attribute on an `input` element:
</form>
```
The password form field must only contain digits (0 to 9) and lowercase alphabets (a to z). No other characters (#,$,&, etc.) are allowed. The rule in RegEx is written as `[a-z]{1,15}`.
The password form field must only contain digits (0 to 9), lowercase alphabets (a to z) and it must be no more than 15 characters in length. No other characters (#,$,&, etc.) are allowed. The rule in RegEx is written as `[a-z0-9]{1,15}`.
![form-validate-regex](https://assets.vercel.com/image/upload/dpr_auto,q_auto,f_auto/nextjs/guides/building-forms/form-validate-regex.jpg)
......@@ -180,13 +180,16 @@ export default function handler(req, res) {
// in the command line where next.js app is running.
console.log('body: ', body)
// Both of these are required.
// Guard clause checks for first and last name,
// and returns early if they are not found
if (!body.first || !body.last) {
return res.json({ data: 'First or last name not found' })
// Sends a HTTP bad request error code
return res.status(400).json({ data: 'First or last name not found' })
}
// Found the name.
res.json({ data: `${body.first} ${body.last}` })
// Sends a HTTP success code
res.status(200).json({ data: `${body.first} ${body.last}` })
}
```
......
......@@ -4,6 +4,16 @@ description: Learn how to use Middleware in Next.js to run code before a request
# Middleware
<details open>
<summary><b>Version History</b></summary>
| Version | Changes |
| --------- | ------------------------------------------------------------------------------------------ |
| `v12.0.9` | Enforce absolute URLs in Edge Runtime ([PR](https://github.com/vercel/next.js/pull/33410)) |
| `v12.0.0` | Middleware (beta) added. |
</details>
Middleware enables you to use code over configuration. This gives you full flexibility in Next.js, because you can run code before a request is completed. Based on the user's incoming request, you can modify the response by rewriting, redirecting, adding headers, or even streaming HTML.
## Usage
......@@ -50,7 +60,7 @@ export type Middleware = (
The function can be a default export and as such, does **not** have to be named `middleware`. Though this is a convention. Also note that you only need to make the function `async` if you are running asynchronous code.
**Note:** Edge Functions are currently in Beta. The API might change as we look to continually make improvements.
[Read the full Middleware API reference.](/docs/api-reference/next/server.md)
## Examples
......
......@@ -14,3 +14,5 @@ For each, you'll want to check if the file is meant to be a page.
If the file is not meant to be a page, and instead, is a shared component or file, move the file to a different folder like `components` or `lib`.
If the file is meant to be a page, double check you have an `export default` with the React Component instead of an `export`. If you're already using `export default`, make sure the returned value is a valid React Component.
If you need to support a different file extension for a page component (such as `.mdx`) or would like to include non-page files in the `pages` directory, configure [Custom Page Extensions](https://nextjs.org/docs/api-reference/next.config.js/custom-page-extensions) in the `next.config.js`.
......@@ -2,7 +2,7 @@ export const EXAMPLE_PATH = 'cms-builder-io'
export const CMS_NAME = 'Builder.io'
export const CMS_URL = 'https://builder.io/'
export const HOME_OG_IMAGE_URL =
'https://og-image.now.sh/Next.js%20Blog%20example%20with%20**Builder.io**.png?theme=light&md=1&fontSize=100px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fnextjs-black-logo.svg&images=https%3A%2F%2Fcdn.builder.io%2Fapi%2Fv1%2Fimage%2Fassets%252FYJIGb4i01jvw0SRdL5Bt%252F79c8b61740bc41d5ae722c000ddb5915'
'https://og-image.vercel.app/Next.js%20Blog%20example%20with%20**Builder.io**.png?theme=light&md=1&fontSize=100px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fnextjs-black-logo.svg&images=https%3A%2F%2Fcdn.builder.io%2Fapi%2Fv1%2Fimage%2Fassets%252FYJIGb4i01jvw0SRdL5Bt%252F79c8b61740bc41d5ae722c000ddb5915'
export const BUILDER_CONFIG = {
apiKey: process.env.NEXT_PUBLIC_BUILDER_API_KEY,
postsModel: 'post',
......
......@@ -4,10 +4,10 @@ This example showcases Next.js's [Static Generation](https://nextjs.org/docs/bas
## Demo
- **Live**: [https://next-blog-prepr.now.sh/](https://next-blog-prepr.now.sh/)
- **Preview Mode**: [https://next-blog-prepr.now.sh/api/preview...](https://next-blog-prepr.now.sh/api/preview?secret=237864ihasdhj283768&slug=discover-enjoy-amsterdam)
- **Live**: [https://next-blog-prepr.vercel.app/](https://next-blog-prepr.vercel.app/)
- **Preview Mode**: [https://next-blog-prepr.vercel.app/api/preview...](https://next-blog-prepr.vercel.app/api/preview?secret=237864ihasdhj283768&slug=discover-enjoy-amsterdam)
### [https://next-blog-prepr.now.sh/](https://next-blog-prepr.now.sh/)
### [https://next-blog-prepr.vercel.app/](https://next-blog-prepr.vercel.app/)
### Related examples
......
......@@ -33,7 +33,7 @@ Once you have access to [the environment variables you'll need](#step-3-set-up-e
## How to use
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example cms-umbraco-heartcore cms-umbraco-heartcore-app
......@@ -91,7 +91,7 @@ yarn install
yarn dev
```
Your blog should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/zeit/next.js/discussions).
Your blog should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/vercel/next.js/discussions).
### Step 5. Try preview mode
......
......@@ -27,7 +27,7 @@ export default function Alert({ preview }) {
<>
The source code for this blog is{' '}
<a
href={`https://github.com/zeit/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
className="underline hover:text-success duration-200 transition-colors"
>
available on GitHub
......
......@@ -17,7 +17,7 @@ export default function Footer() {
Read Documentation
</a>
<a
href={`https://github.com/zeit/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
className="mx-3 font-bold hover:underline"
>
View on GitHub
......
......@@ -2,4 +2,4 @@ export const EXAMPLE_PATH = 'cms-umbraco-heartcore'
export const CMS_NAME = 'Umbraco Heartcore'
export const CMS_URL = 'https://umbraco.com/heartcore'
export const HOME_OG_IMAGE_URL =
'https://og-image.now.sh/Next.js%20Blog%20Example%20with%20**Umbraco%20Heartcore**.png?theme=light&md=1&fontSize=100px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fnextjs-black-logo.svg&images=https://media.umbraco.io/demo-headless/8d8a349dde73ca6/u_heartcore_heart_lockup_tagline_dark.svg'
'https://og-image.vercel.app/Next.js%20Blog%20Example%20with%20**Umbraco%20Heartcore**.png?theme=light&md=1&fontSize=100px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fnextjs-black-logo.svg&images=https://media.umbraco.io/demo-headless/8d8a349dde73ca6/u_heartcore_heart_lockup_tagline_dark.svg'
......@@ -24,7 +24,7 @@ export default function Home() {
1. <b>no `getInitialProps`</b> to ensure every page is static
<br />
2. <b>`useUser` hook</b> together with `
<a href="https://swr.now.sh/">swr`</a> for data fetching
<a href="https://swr.vercel.app/">swr`</a> for data fetching
</p>
<h2>Features</h2>
......
......@@ -2,7 +2,6 @@ import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-ut
import chalk from 'next/dist/compiled/chalk'
import crypto from 'crypto'
import { stringify } from 'querystring'
import semver from 'next/dist/compiled/semver'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import path, { join as pathJoin, relative as relativePath } from 'path'
......@@ -15,7 +14,6 @@ import {
MIDDLEWARE_ROUTE,
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { getPackageVersion } from '../lib/get-package-version'
import { CustomRoutes } from '../lib/load-custom-routes.js'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
......@@ -52,6 +50,7 @@ import type { Span } from '../trace'
import { getRawPageExtensions } from './utils'
import browserslist from 'next/dist/compiled/browserslist'
import loadJsConfig from './load-jsconfig'
import { shouldUseReactRoot } from '../server/config'
const watchOptions = Object.freeze({
aggregateTimeout: 5,
......@@ -337,21 +336,7 @@ export default async function getBaseWebpackConfig(
rewrites.afterFiles.length > 0 ||
rewrites.fallback.length > 0
const hasReactRefresh: boolean = dev && !isServer
const reactDomVersion = await getPackageVersion({
cwd: dir,
name: 'react-dom',
})
const isReactExperimental = Boolean(
reactDomVersion && /0\.0\.0-experimental/.test(reactDomVersion)
)
const hasReact18: boolean =
Boolean(reactDomVersion) &&
(semver.gte(reactDomVersion!, '18.0.0') ||
semver.coerce(reactDomVersion)?.version === '18.0.0')
const hasReactRoot: boolean =
config.experimental.reactRoot || hasReact18 || isReactExperimental
const hasReactRoot = shouldUseReactRoot()
const runtime = config.experimental.runtime
// Make sure reactRoot is enabled when react 18 is detected
......@@ -360,11 +345,7 @@ export default async function getBaseWebpackConfig(
}
// Only inform during one of the builds
if (
!isServer &&
config.experimental.reactRoot &&
!(hasReact18 || isReactExperimental)
) {
if (!isServer && config.experimental.reactRoot && !hasReactRoot) {
// It's fine to only mention React 18 here as we don't recommend people to try experimental.
Log.warn('You have to use React 18 to use `experimental.reactRoot`.')
}
......@@ -1365,9 +1346,6 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify(
config.optimizeFonts && !dev
),
'process.env.__NEXT_OPTIMIZE_IMAGES': JSON.stringify(
config.experimental.optimizeImages
),
'process.env.__NEXT_OPTIMIZE_CSS': JSON.stringify(
config.experimental.optimizeCss && !dev
),
......@@ -1630,7 +1608,6 @@ export default async function getBaseWebpackConfig(
reactStrictMode: config.reactStrictMode,
reactMode: config.experimental.reactMode,
optimizeFonts: config.optimizeFonts,
optimizeImages: config.experimental.optimizeImages,
optimizeCss: config.experimental.optimizeCss,
scrollRestoration: config.experimental.scrollRestoration,
basePath: config.basePath,
......
......@@ -72,6 +72,7 @@ export function getRender({
webServerConfig: {
extendRenderOpts: {
buildId,
reactRoot: true,
runtime: 'edge',
supportsDynamicHTML: true,
disableOptimizedLoading: true,
......
......@@ -191,7 +191,6 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
locale: detectedLocale,
defaultLocale,
domainLocales: i18n?.domains,
optimizeImages: process.env.__NEXT_OPTIMIZE_IMAGES,
optimizeCss: process.env.__NEXT_OPTIMIZE_CSS,
crossOrigin: process.env.__NEXT_CROSS_ORIGIN,
},
......
......@@ -350,5 +350,6 @@ function hasAlreadyWarnedAboutFullRefresh() {
}
function clearFullRefreshStorage() {
sessionStorage.removeItem(FULL_REFRESH_STORAGE_KEY)
if (sessionStorage.getItem(FULL_REFRESH_STORAGE_KEY) !== 'ignore')
sessionStorage.removeItem(FULL_REFRESH_STORAGE_KEY)
}
......@@ -775,9 +775,11 @@ if (process.env.__NEXT_RSC) {
serialized?: string
_fresh?: boolean
}) => {
React.useEffect(() => {
rscCache.delete(cacheKey)
})
const response = useServerResponse(cacheKey, serialized)
const root = response.readRoot()
rscCache.delete(cacheKey)
return root
}
......
......@@ -7,7 +7,7 @@ export function RouteAnnouncer() {
// Only announce the path change, but not for the first load because screen
// reader will do that automatically.
const initialPathLoaded = React.useRef(false)
const previouslyLoadedPath = React.useRef(asPath)
// Every time the path changes, announce the new page’s title following this
// priority: first the document title (from head), otherwise the first h1, or
......@@ -17,10 +17,9 @@ export function RouteAnnouncer() {
// https://www.gatsbyjs.com/blog/2019-07-11-user-testing-accessible-client-routing/
React.useEffect(
() => {
if (!initialPathLoaded.current) {
initialPathLoaded.current = true
return
}
// If the path hasn't change, we do nothing.
if (previouslyLoadedPath.current === asPath) return
previouslyLoadedPath.current = asPath
if (document.title) {
setRouteAnnouncement(document.title)
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -385,7 +385,6 @@ export default async function exportApp(
crossOrigin: nextConfig.crossOrigin,
optimizeCss: nextConfig.experimental.optimizeCss,
optimizeFonts: nextConfig.optimizeFonts,
optimizeImages: nextConfig.experimental.optimizeImages,
reactRoot: nextConfig.experimental.reactRoot || false,
}
......@@ -583,7 +582,6 @@ export default async function exportApp(
buildExport: options.buildExport,
serverless: isTargetLikeServerless(nextConfig.target),
optimizeFonts: nextConfig.optimizeFonts,
optimizeImages: nextConfig.experimental.optimizeImages,
optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading:
nextConfig.experimental.disableOptimizedLoading,
......
......@@ -55,7 +55,6 @@ interface ExportPageInput {
subFolders?: boolean
serverless: boolean
optimizeFonts: boolean
optimizeImages?: boolean
optimizeCss: any
disableOptimizedLoading: any
parentSpanId: any
......@@ -77,7 +76,6 @@ interface RenderOpts {
ampValidatorPath?: string
ampSkipValidation?: boolean
optimizeFonts?: boolean
optimizeImages?: boolean
disableOptimizedLoading?: boolean
optimizeCss?: any
fontManifest?: FontManifest
......@@ -105,7 +103,6 @@ export default async function exportPage({
subFolders,
serverless,
optimizeFonts,
optimizeImages,
optimizeCss,
disableOptimizedLoading,
httpAgentOptions,
......@@ -304,8 +301,6 @@ export default async function exportPage({
/// @ts-ignore
optimizeFonts,
/// @ts-ignore
optimizeImages,
/// @ts-ignore
optimizeCss,
disableOptimizedLoading,
distDir,
......@@ -367,9 +362,6 @@ export default async function exportPage({
if (optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
}
if (optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
}
if (optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
......@@ -379,7 +371,6 @@ export default async function exportPage({
ampPath: renderAmpPath,
params,
optimizeFonts,
optimizeImages,
optimizeCss,
disableOptimizedLoading,
fontManifest: optimizeFonts
......
......@@ -494,7 +494,6 @@ export class Head extends Component<
useMaybeDeferContent,
optimizeCss,
optimizeFonts,
optimizeImages,
runtime,
} = this.context
......@@ -737,7 +736,6 @@ export class Head extends Component<
)}
{!optimizeCss && this.getCssLinks(files)}
{!optimizeCss && <noscript data-n-css={this.props.nonce ?? ''} />}
{optimizeImages && <meta name="next-image-preload" />}
{!isDeferred && getDynamicScriptPreloads()}
......
......@@ -152,7 +152,6 @@ export default abstract class Server {
optimizeFonts: boolean
images: ImageConfigComplete
fontManifest?: FontManifest
optimizeImages: boolean
disableOptimizedLoading?: boolean
optimizeCss: any
locale?: string
......@@ -314,7 +313,6 @@ export default abstract class Server {
this.nextConfig.optimizeFonts && !dev
? this.getFontManifest()
: undefined,
optimizeImages: !!this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss,
disableOptimizedLoading: this.nextConfig.experimental.runtime
? true
......
......@@ -85,7 +85,6 @@ export interface ExperimentalConfig {
reactMode?: 'legacy' | 'concurrent' | 'blocking'
workerThreads?: boolean
pageEnv?: boolean
optimizeImages?: boolean
optimizeCss?: boolean
scrollRestoration?: boolean
externalDir?: boolean
......@@ -454,7 +453,6 @@ export const defaultConfig: NextConfig = {
isrFlushToDisk: true,
workerThreads: false,
pageEnv: false,
optimizeImages: false,
optimizeCss: false,
scrollRestoration: false,
externalDir: false,
......
import chalk from '../lib/chalk'
import findUp from 'next/dist/compiled/find-up'
import { basename, extname, relative, isAbsolute, resolve } from 'path'
import { pathToFileURL } from 'url'
import { Agent as HttpAgent } from 'http'
import { Agent as HttpsAgent } from 'https'
import semver from 'next/dist/compiled/semver'
import findUp from 'next/dist/compiled/find-up'
import chalk from '../lib/chalk'
import * as Log from '../build/output/log'
import { CONFIG_FILES, PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils'
......@@ -653,6 +654,11 @@ export default async function loadConfig(
)
}
const hasReactRoot = shouldUseReactRoot()
if (hasReactRoot) {
userConfig.experimental.reactRoot = true
}
if (userConfig.amp?.canonicalBase) {
const { canonicalBase } = userConfig.amp || ({} as any)
userConfig.amp = userConfig.amp || {}
......@@ -698,6 +704,19 @@ export default async function loadConfig(
return completeConfig
}
export function shouldUseReactRoot() {
const reactDomVersion = require('react-dom').version
const isReactExperimental = Boolean(
reactDomVersion && /0\.0\.0-experimental/.test(reactDomVersion)
)
const hasReact18: boolean =
Boolean(reactDomVersion) &&
(semver.gte(reactDomVersion!, '18.0.0') ||
semver.coerce(reactDomVersion)?.version === '18.0.0')
return hasReact18 || isReactExperimental
}
export function setHttpAgentOptions(
options: NextConfigComplete['httpAgentOptions']
) {
......
......@@ -940,7 +940,9 @@ export default class DevServer extends Server {
// Build the error page to ensure the fallback is built too.
// TODO: See if this can be moved into hotReloader or removed.
await this.hotReloader!.ensurePage('/_error')
return await loadDefaultErrorComponents(this.distDir)
return await loadDefaultErrorComponents(this.distDir, {
hasConcurrentFeatures: !!this.renderOpts.runtime,
})
}
protected setImmutableAssetCacheControl(res: BaseNextResponse): void {
......
......@@ -34,8 +34,14 @@ export type LoadComponentsReturnType = {
ComponentMod: any
}
export async function loadDefaultErrorComponents(distDir: string) {
const Document = interopDefault(require('next/dist/pages/_document'))
export async function loadDefaultErrorComponents(
distDir: string,
{ hasConcurrentFeatures }: { hasConcurrentFeatures: boolean }
) {
const Document = interopDefault(
require(`next/dist/pages/_document` +
(hasConcurrentFeatures ? '-concurrent' : ''))
)
const App = interopDefault(require('next/dist/pages/_app'))
const ComponentMod = require('next/dist/pages/_error')
const Component = interopDefault(ComponentMod)
......
......@@ -100,15 +100,11 @@ export default class NextNodeServer extends BaseServer {
/**
* This sets environment variable to be used at the time of SSR by head.tsx.
* Using this from process.env allows targeting both serverless and SSR by calling
* `process.env.__NEXT_OPTIMIZE_IMAGES`.
* TODO(atcastle@): Remove this when experimental.optimizeImages are being cleaned up.
* `process.env.__NEXT_OPTIMIZE_CSS`.
*/
if (this.renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
}
if (this.renderOpts.optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
}
if (this.renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
......
......@@ -215,7 +215,6 @@ export type RenderOptsPartial = {
unstable_JsPreload?: false
optimizeFonts: boolean
fontManifest?: FontManifest
optimizeImages: boolean
optimizeCss: any
devOnlyCacheBusterQueryString?: string
resolvedUrl?: string
......@@ -1406,7 +1405,6 @@ export async function renderToHTML(
crossOrigin: renderOpts.crossOrigin,
optimizeCss: renderOpts.optimizeCss,
optimizeFonts: renderOpts.optimizeFonts,
optimizeImages: renderOpts.optimizeImages,
runtime,
}
......@@ -1485,16 +1483,13 @@ export async function renderToHTML(
return html
}
: null,
!process.browser &&
(process.env.__NEXT_OPTIMIZE_FONTS ||
process.env.__NEXT_OPTIMIZE_IMAGES)
!process.browser && process.env.__NEXT_OPTIMIZE_FONTS
? async (html: string) => {
return await postProcess(
html,
{ getFontDefinition },
{
optimizeFonts: renderOpts.optimizeFonts,
optimizeImages: renderOpts.optimizeImages,
}
)
}
......
import { escapeStringRegexp } from './escape-regexp'
import { parse, HTMLElement } from 'next/dist/compiled/node-html-parser'
import { OPTIMIZED_FONT_PROVIDERS } from './constants'
// const MIDDLEWARE_TIME_BUDGET = parseInt(process.env.__POST_PROCESS_MIDDLEWARE_TIME_BUDGET || '', 10) || 10
const MAXIMUM_IMAGE_PRELOADS = 2
const IMAGE_PRELOAD_SIZE_THRESHOLD = 2500
type postProcessOptions = {
optimizeFonts: boolean
optimizeImages: boolean
}
type renderOptions = {
......@@ -169,103 +165,6 @@ class FontOptimizerMiddleware implements PostProcessMiddleware {
}
}
class ImageOptimizerMiddleware implements PostProcessMiddleware {
inspect(originalDom: HTMLElement) {
const imgPreloads = []
const imgElements = originalDom.querySelectorAll('img')
let eligibleImages: Array<HTMLElement> = []
for (let i = 0; i < imgElements.length; i++) {
if (isImgEligible(imgElements[i])) {
eligibleImages.push(imgElements[i])
}
if (eligibleImages.length >= MAXIMUM_IMAGE_PRELOADS) {
break
}
}
for (const imgEl of eligibleImages) {
const src = imgEl.getAttribute('src')
if (src) {
imgPreloads.push(src)
}
}
return imgPreloads
}
mutate = async (markup: string, imgPreloads: string[]) => {
let result = markup
let imagePreloadTags = imgPreloads
.filter((imgHref) => !preloadTagAlreadyExists(markup, imgHref))
.reduce(
(acc, imgHref) =>
acc + `<link rel="preload" href="${imgHref}" as="image"/>`,
''
)
return result.replace('<meta name="next-image-preload"/>', imagePreloadTags)
}
}
function isImgEligible(imgElement: HTMLElement): boolean {
let imgSrc = imgElement.getAttribute('src')
return (
!!imgSrc &&
sourceIsSupportedType(imgSrc) &&
imageIsNotTooSmall(imgElement) &&
imageIsNotHidden(imgElement)
)
}
function preloadTagAlreadyExists(html: string, href: string) {
const escapedHref = escapeStringRegexp(href)
const regex = new RegExp(`<link[^>]*href[^>]*${escapedHref}`)
return html.match(regex)
}
function imageIsNotTooSmall(imgElement: HTMLElement): boolean {
// Skip images without both height and width--we don't know enough to say if
// they are too small
if (
!(imgElement.hasAttribute('height') && imgElement.hasAttribute('width'))
) {
return true
}
try {
const heightAttr = imgElement.getAttribute('height')
const widthAttr = imgElement.getAttribute('width')
if (!heightAttr || !widthAttr) {
return true
}
if (
parseInt(heightAttr) * parseInt(widthAttr) <=
IMAGE_PRELOAD_SIZE_THRESHOLD
) {
return false
}
} catch (err) {
return true
}
return true
}
// Traverse up the dom from each image to see if it or any of it's
// ancestors have the hidden attribute.
function imageIsNotHidden(imgElement: HTMLElement): boolean {
let activeElement = imgElement
while (activeElement.parentNode) {
if (activeElement.hasAttribute('hidden')) {
return false
}
activeElement = activeElement.parentNode as HTMLElement
}
return true
}
// Currently only filters out svg images--could be made more specific in the future.
function sourceIsSupportedType(imgSrc: string): boolean {
return !imgSrc.includes('.svg')
}
// Initialization
registerPostProcessor(
'Inline-Fonts',
......@@ -275,11 +174,4 @@ registerPostProcessor(
(options) => options.optimizeFonts || process.env.__NEXT_OPTIMIZE_FONTS
)
registerPostProcessor(
'Preload Images',
new ImageOptimizerMiddleware(),
// @ts-ignore
(options) => options.optimizeImages || process.env.__NEXT_OPTIMIZE_IMAGES
)
export default processHTML
......@@ -224,7 +224,6 @@ export type HtmlProps = {
crossOrigin?: string
optimizeCss?: boolean
optimizeFonts?: boolean
optimizeImages?: boolean
runtime?: 'edge' | 'nodejs'
}
......
......@@ -12,11 +12,19 @@ import { noop as css } from '../helpers/noop-template'
export type FullRefreshWarningProps = { reason: string | null }
const FULL_REFRESH_STORAGE_KEY = '_has_warned_about_full_refresh'
export const FullRefreshWarning: React.FC<FullRefreshWarningProps> =
function FullRefreshWarning({ reason }) {
const reload = React.useCallback(() => {
window.location.reload()
}, [])
const change = React.useCallback((e) => {
sessionStorage.setItem(
FULL_REFRESH_STORAGE_KEY,
e.target.checked ? 'ignore' : 'true'
)
}, [])
return (
<Overlay fixed>
......@@ -42,6 +50,10 @@ export const FullRefreshWarning: React.FC<FullRefreshWarningProps> =
</a>
.
</p>
<label>
<input type="checkbox" onChange={change} /> Don't show again
for session
</label>
<button onClick={reload}>Reload</button>
</footer>
</DialogBody>
......
......@@ -10,6 +10,7 @@ import webdriver from 'next-webdriver'
import { join } from 'path'
const context = {}
const appDir = join(__dirname, '../')
const navigateTo = async (browser, selector) =>
await browser
......@@ -28,7 +29,7 @@ const getMainHeadingTitle = async (browser) =>
describe('Client Navigation accessibility', () => {
beforeAll(async () => {
context.appPort = await findPort()
context.server = await launchApp(join(__dirname, '../'), context.appPort, {
context.server = await launchApp(appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
})
......@@ -44,6 +45,12 @@ describe('Client Navigation accessibility', () => {
afterAll(() => killApp(context.server))
describe('<RouteAnnouncer />', () => {
it('should not have the initial route announced', async () => {
const browser = await webdriver(context.appPort, '/')
const title = await getAnnouncedTitle(browser)
expect(title).toBe('')
})
it('has aria-live="assertive" and role="alert"', async () => {
const browser = await webdriver(context.appPort, '/')
const routeAnnouncer = await browser.waitForElementByCss(
......
module.exports = {
target: 'serverless',
experimental: { optimizeImages: true },
}
import React from 'react'
const Page = () => {
return (
<div>
<link rel="preload" href="already-preloaded.jpg" />
<img src="already-preloaded.jpg" />
<img src="tiny-image.jpg" width="20" height="20" />
<img src="vector-image.svg" />
<img src="hidden-image-1.jpg" hidden />
<div hidden>
<img src="hidden-image-2.jpg" />
</div>
<img src="main-image-1.jpg" />
<div>
<img src="main-image-2.jpg" />
</div>
<img src="main-image-3.jpg" />
<img src="main-image-4.jpg" />
<img src="main-image-5.jpg" />
</div>
)
}
export default Page
function Home({ stars }) {
return (
<div className="container">
<main>
<div>
<link rel="preload" href="already-preloaded.jpg" />
<img src="already-preloaded.jpg" />
<img src="tiny-image.jpg" width="20" height="20" />
<img src="vector-image.svg" />
<img src="hidden-image-1.jpg" hidden />
<div hidden>
<img src="hidden-image-2.jpg" />
</div>
<img src="main-image-1.jpg" />
<img src="main-image-2.jpg" />
<img src="main-image-3.jpg" />
<img src="main-image-4.jpg" />
<img src="main-image-5.jpg" />
</div>
<div>Next stars: {stars}</div>
</main>
</div>
)
}
Home.getInitialProps = async () => {
return { stars: Math.random() * 1000 }
}
export default Home
import React from 'react'
import Head from 'next/head'
const Page = () => {
return (
<>
<Head>
<link
href="https://fonts.googleapis.com/css2?family=Modak"
rel="stylesheet"
/>
</Head>
<div>Hi!</div>
</>
)
}
export default Page
import React from 'react'
const Page = () => {
return (
<div>
<img src="https://image.example.org/?lang[]=c++" />
<img src="/api/image?lang[]=c++" />
</div>
)
}
export default Page
/* eslint-env jest */
import { join } from 'path'
import {
killApp,
findPort,
nextStart,
nextBuild,
renderViaHTTP,
} from 'next-test-utils'
import fs from 'fs-extra'
const appDir = join(__dirname, '../')
const nextConfig = join(appDir, 'next.config.js')
let appPort
let app
function runTests() {
describe('On a static page', () => {
checkImagesOnPage('/')
})
describe('On an SSR page', () => {
checkImagesOnPage('/stars')
})
describe('On a static page with querystring ', () => {
it('should preload exactly eligible image', async () => {
const html = await renderViaHTTP(appPort, '/with-querystring')
expect(html).toContain(
'<link rel="preload" href="https://image.example.org/?lang[]=c++" as="image"/>'
)
expect(html).toContain(
'<link rel="preload" href="/api/image?lang[]=c++" as="image"/>'
)
})
})
}
function checkImagesOnPage(path) {
it('should not preload tiny images', async () => {
const html = await renderViaHTTP(appPort, path)
expect(html).not.toContain(
'<link rel="preload" href="tiny-image.jpg" as="image"/>'
)
})
it('should not add a preload if one already exists', async () => {
let html = await renderViaHTTP(appPort, path)
html = html.replace(
'<link rel="preload" href="already-preloaded.jpg" as="image"/>',
''
)
expect(html).not.toContain(
'<link rel="preload" href="already-preloaded.jpg" as="image"/>'
)
})
it('should not preload hidden images', async () => {
const html = await renderViaHTTP(appPort, path)
expect(html).not.toContain(
'<link rel="preload" href="hidden-image-1.jpg" as="image"/>'
)
expect(html).not.toContain(
'<link rel="preload" href="hidden-image-2.jpg" as="image"/>'
)
})
it('should not preload SVG images', async () => {
const html = await renderViaHTTP(appPort, path)
expect(html).not.toContain(
'<link rel="preload" href="vector-image.svg" as="image"/>'
)
})
it('should preload exactly two eligible images', async () => {
const html = await renderViaHTTP(appPort, path)
expect(html).toContain(
'<link rel="preload" href="main-image-1.jpg" as="image"/>'
)
expect(html).not.toContain(
'<link rel="preload" href="main-image-2.jpg" as="image"/>'
)
})
}
describe('Image optimization for SSR apps', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfig,
`module.exports = { experimental: {optimizeImages: true} }`,
'utf8'
)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('Image optimization for serverless apps', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfig,
`module.exports = { target: 'serverless', experimental: {optimizeImages: true} }`,
'utf8'
)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
const withReact18 = require('../test/with-react-18')
module.exports = withReact18({
// reactStrictMode: true,
experimental: {
reactRoot: true,
// runtime: 'edge',
......
/* eslint-env jest */
import { join } from 'path'
import fs from 'fs-extra'
import {
File,
......@@ -16,6 +15,7 @@ import {
import blocking from './blocking'
import concurrent from './concurrent'
import basics from './basics'
import strictMode from './strict-mode'
// overrides react and react-dom to v18
const nodeArgs = ['-r', join(__dirname, 'require-hook.js')]
......@@ -57,12 +57,11 @@ async function getDevOutput(dir) {
describe('React 18 Support', () => {
describe('Use legacy render', () => {
beforeAll(async () => {
await fs.remove(join(appDir, 'node_modules'))
beforeAll(() => {
nextConfig.replace('reactRoot: true', 'reactRoot: false')
})
afterAll(() => {
nextConfig.replace('reactRoot: false', 'reactRoot: true')
nextConfig.restore()
})
test('supported version of react in dev', async () => {
......@@ -75,15 +74,17 @@ describe('React 18 Support', () => {
expect(output).not.toMatch(USING_CREATE_ROOT)
})
test('suspense is not allowed in blocking rendering mode (prod)', async () => {
test('suspense is not allowed in blocking rendering mode', async () => {
nextConfig.replace('withReact18({', '/*withReact18*/({')
const { stderr, code } = await nextBuild(appDir, [], {
nodeArgs,
stderr: true,
})
expect(code).toBe(1)
nextConfig.replace('/*withReact18*/({', 'withReact18({')
expect(stderr).toContain(
'Invalid suspense option usage in next/dynamic. Read more: https://nextjs.org/docs/messages/invalid-dynamic-suspense'
)
expect(code).toBe(1)
})
})
})
......@@ -106,6 +107,26 @@ describe('Basics', () => {
})
})
// React 18 with Strict Mode enabled might cause double invocation of lifecycle methods.
describe('Strict mode - dev', () => {
const context = { appDir }
beforeAll(async () => {
nextConfig.replace('// reactStrictMode: true,', 'reactStrictMode: true,')
context.appPort = await findPort()
context.server = await launchApp(context.appDir, context.appPort, {
nodeArgs,
})
})
afterAll(() => {
nextConfig.restore()
killApp(context.server)
})
strictMode(context)
})
describe('Blocking mode', () => {
beforeAll(() => {
dynamicHello.replace('suspense = false', `suspense = true`)
......@@ -119,56 +140,58 @@ describe('Blocking mode', () => {
)
})
describe('Concurrent mode in the edge runtime', () => {
beforeAll(async () => {
nextConfig.replace("// runtime: 'edge'", "runtime: 'edge'")
dynamicHello.replace('suspense = false', `suspense = true`)
// `noSSR` mode will be ignored by suspense
dynamicHello.replace('let ssr', `let ssr = false`)
})
afterAll(async () => {
nextConfig.restore()
dynamicHello.restore()
})
function runTestsAgainstRuntime(runtime) {
describe(`Concurrent mode in the ${runtime} runtime`, () => {
beforeAll(async () => {
nextConfig.replace("// runtime: 'edge'", `runtime: '${runtime}'`)
dynamicHello.replace('suspense = false', `suspense = true`)
// `noSSR` mode will be ignored by suspense
dynamicHello.replace('let ssr', `let ssr = false`)
})
afterAll(async () => {
nextConfig.restore()
dynamicHello.restore()
})
runTests('`runtime` is set to `edge`', (context) => {
concurrent(context, (p, q) => renderViaHTTP(context.appPort, p, q))
runTests(`runtime is set to '${runtime}'`, (context) => {
concurrent(context, (p, q) => renderViaHTTP(context.appPort, p, q))
it('should stream to users', async () => {
const res = await fetchViaHTTP(context.appPort, '/ssr')
expect(res.headers.get('etag')).toBeNull()
})
it('should stream to users', async () => {
const res = await fetchViaHTTP(context.appPort, '/ssr')
expect(res.headers.get('etag')).toBeNull()
})
it('should not stream to bots', async () => {
const res = await fetchViaHTTP(
context.appPort,
'/ssr',
{},
{
headers: {
'user-agent': 'Googlebot',
},
}
)
expect(res.headers.get('etag')).toBeDefined()
})
it('should not stream to bots', async () => {
const res = await fetchViaHTTP(
context.appPort,
'/ssr',
{},
{
headers: {
'user-agent': 'Googlebot',
},
}
)
expect(res.headers.get('etag')).toBeDefined()
})
it('should not stream to google pagerender bot', async () => {
const res = await fetchViaHTTP(
context.appPort,
'/ssr',
{},
{
headers: {
'user-agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 Google-PageRenderer Google (+https://developers.google.com/+/web/snippet/)',
},
}
)
expect(res.headers.get('etag')).toBeDefined()
it('should not stream to google pagerender bot', async () => {
const res = await fetchViaHTTP(
context.appPort,
'/ssr',
{},
{
headers: {
'user-agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 Google-PageRenderer Google (+https://developers.google.com/+/web/snippet/)',
},
}
)
expect(res.headers.get('etag')).toBeDefined()
})
})
})
})
}
function runTest(mode, name, fn) {
const context = { appDir }
......@@ -200,6 +223,9 @@ function runTest(mode, name, fn) {
})
}
runTestsAgainstRuntime('edge')
runTestsAgainstRuntime('nodejs')
function runTests(name, fn) {
runTest('dev', name, fn)
runTest('prod', name, fn)
......
/* eslint-env jest */
import webdriver from 'next-webdriver'
export default (context) => {
describe('<RouteAnnouncer />', () => {
it('should not have the initial route announced', async () => {
const browser = await webdriver(context.appPort, '/')
const title = await browser
.waitForElementByCss('#__next-route-announcer__')
.text()
expect(title).toBe('')
})
})
}
module.exports = function withReact18(config) {
if (typeof config.experimental.reactRoot === 'undefined') {
config.experimental.reactRoot = true
}
config.webpack = (webpackConfig) => {
const { alias } = webpackConfig.resolve
// FIXME: resolving react/jsx-runtime https://github.com/facebook/react/issues/20235
......
const withReact18 = require('../../react-18/test/with-react-18')
module.exports = withReact18({
reactStrictMode: true,
onDemandEntries: {
maxInactiveAge: 1000 * 60 * 60,
},
pageExtensions: ['js', 'ts', 'jsx'], // .tsx won't be treat as page,
experimental: {
reactRoot: true,
serverComponents: true,
runtime: 'edge',
},
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment