Skip to content

Commit

Permalink
Merge branch 'canary' into fix/eslint-error-url
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk committed Sep 12, 2022
2 parents 918938e + 7355757 commit 8e1c077
Show file tree
Hide file tree
Showing 16 changed files with 135 additions and 384 deletions.
5 changes: 3 additions & 2 deletions docs/advanced-features/compiler.md
Expand Up @@ -9,6 +9,7 @@ description: Learn about the Next.js Compiler, written in Rust, which transforms

| Version | Changes |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `v12.3.0` | SWC Minifier [stable](https://nextjs.org/blog/next-12-3#swc-minifier-stable). |
| `v12.2.0` | [SWC Plugins](#swc-plugins-Experimental) experimental support added. |
| `v12.1.0` | Added support for Styled Components, Jest, Relay, Remove React Properties, Legacy Decorators, Remove Console, and jsxImportSource. |
| `v12.0.0` | Next.js Compiler [introduced](https://nextjs.org/blog/next-12). |
Expand Down Expand Up @@ -238,8 +239,6 @@ module.exports = {

Only `importMap` in `@emotion/babel-plugin` is not supported for now.

## Experimental Features

### Minification

You can opt-in to using the Next.js compiler for minification. This is 7x faster than Terser.
Expand All @@ -254,6 +253,8 @@ module.exports = {

If you have feedback about `swcMinify`, please share it on the [feedback discussion](https://github.com/vercel/next.js/discussions/30237).

## Experimental Features

### Minifier debug options

While the minifier is experimental, we are making the following options available for debugging purposes. They will not be available once the minifier is made stable.
Expand Down
115 changes: 13 additions & 102 deletions docs/advanced-features/react-18/server-components.md
@@ -1,116 +1,27 @@
# React Server Components (RFC)

Server Components allow us to render React components on the server. This is fundamentally different from server-side rendering (SSR) where you're pre-generating HTML on the server. With Server Components, there's **zero client-side JavaScript needed,** making page rendering faster. This improves the user experience of your application, pairing the best parts of server-rendering with client-side interactivity.
React Server Components allow developers to build applications that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering.

### Next Router and Layouts RFC
In an upcoming Next.js release, React and Next.js developers will be able to use Server Components inside the `app` directory as part of the changes outlined by the [Layouts RFC](https://nextjs.org/blog/layouts-rfc).

We are currently implementing the [Next.js Router and Layouts RFC](https://nextjs.org/blog/layouts-rfc).
## What are React Server Components?

The new Next.js router will be built on top of React 18 features, including React Server Components.
React Server Components improve the user experience of your application by pairing the best parts of server-rendering with client-side interactivity.

One of the biggest proposed changes is that, by default, files inside a new `app` directory will be rendered on the server as React Server Components.
With traditional React applications that are client-side only, developers often had to make tradeoffs between SEO and performance. Server Components enable developers to better leverage their server infrastructure and achieve great performance by default.

This will allow you to automatically adopt React Server Components when migrating from `pages` to `app`.
For example, large dependencies that previously would impact the JavaScript bundle size on the client can instead stay entirely on the server. By sending less JavaScript to the browser, the time to interactive for the page is decreased, leading to improved [Core Web Vitals](https://vercel.com/blog/core-web-vitals).

You can find more information on the [RFC](https://nextjs.org/blog/layouts-rfc) and we welcome your feedback on [Github Discussions](https://github.com/vercel/next.js/discussions/37136).
## React Server Components vs Server-Side Rendering

### Server Components Conventions
[Server-side Rendering](/docs/basic-features/pages.md#server-side-rendering) (SSR) dynamically builds your application into HTML on the server. This creates faster load times for users by offloading work from the user's device to the server, especially those with slower internet connections or older devices. However, developers still pay the cost to download, parse, and hydrate those components after the initial HTML loads.

To run a component on the server, append `.server.js` to the end of the filename. For example, `./pages/home.server.js` will be treated as a Server Component.
React Server Components, combined with Next.js server-side rendering, help eliminate the tradeoff of all-or-nothing data fetching. You can progressively show updates as your data comes in.

For client components, append `.client.js` to the filename. For example, `./components/avatar.client.js`.
## Using React Server Components with Next.js

Server components can import server components and client components.
The Next.js team at Vercel released the [Layouts RFC](https://nextjs.org/blog/layouts-rfc) a few months ago outlining the vision for the future of routing, layouts, and data fetching in the framework. These changes **aren't available yet**, but we can start learning about how they will be used.

Client components **cannot** import server components.
Pages and Layouts in `app` will be rendered as React Server Components by default. This improves performance by reducing the amount of JavaScript sent to the client for components that are not interactive. Client components will be able to be defined through either a file name extension or through a string literal in the file.

Components without a `server` or `client` extension will be treated as shared components and can be imported by server components and client components. For example:

```jsx
// pages/home.server.js

import { Suspense } from 'react'

import Profile from '../components/profile.server'
import Content from '../components/content.client'

export default function Home() {
return (
<div>
<h1>Welcome to React Server Components</h1>
<Suspense fallback={'Loading...'}>
<Profile />
</Suspense>
<Content />
</div>
)
}
```

The `<Home>` and `<Profile>` components will always be server-side rendered and streamed to the client, and will not be included by the client-side JavaScript. However, `<Content>` will still be hydrated on the client-side, like normal React components.

> Make sure you're using default imports and exports for server components (`.server.js`). The support of named exports are a work in progress!
To see a full example, check out the [vercel/next-react-server-components demo](https://github.com/vercel/next-react-server-components).

## Supported Next.js APIs

### `next/link` and `next/image`

You can use `next/link` and `next/image` like before and they will be treated as client components to keep the interaction on client side.

### `next/document`

If you have a custom `_document`, you have to change your `_document` to a functional component like below to use server components. If you don't have one, Next.js will use the default `_document` component for you.

```jsx
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
```

### `next/app`

The usage of `_app.js` is the same as [Custom App](/docs/advanced-features/custom-app). Using custom app as server component such as `_app.server.js` is not recommended, to keep align with non server components apps for client specific things like global CSS imports.

### Routing

Both basic routes with path and queries and dynamic routes are supported. If you need to access the router in server components(`.server.js`), they will receive `router` instance as a prop so that you can directly access them without using the `useRouter()` hook.

```jsx
// pages/index.server.js

export default function Index({ router }) {
// You can access routing information by `router.pathname`, etc.
return 'hello'
}
```

### Unsupported Next.js APIs

While RSC and SSR streaming are still in the alpha stage, not all Next.js APIs are supported. The following Next.js APIs have limited functionality within Server Components. React 18 use without SSR streaming is not affected.

#### React internals

Most React hooks, such as `useContext`, `useState`, `useReducer`, `useEffect` and `useLayoutEffect`, are not supported as of today since server components are executed per request and aren't stateful.

#### Data Fetching & Styling

Like streaming SSR, styling and data fetching within `Suspense` on the server side are not well supported. We're still working on them.

Page level exported methods like `getInitialProps`, `getStaticProps` and `getStaticPaths` are not supported.

#### `next/head` and I18n

We are still working on support for these features.
We will be providing more updates about Server Components usage in Next.js soon.
2 changes: 1 addition & 1 deletion docs/api-reference/next/server.md
Expand Up @@ -10,7 +10,7 @@ description: Learn about the server-only helpers for Middleware and Edge API Rou

The `NextRequest` object is an extension of the native [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) interface, with the following added methods and properties:

- `cookies` - A [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) with cookies from the `Request`. See [Using cookies in Edge Middleware](#using-cookies-in-edge-middleware)
- `cookies` - A [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) with cookies from the `Request`. See [Using cookies in Middleware](/docs/advanced-features/middleware#using-cookies)
- `nextUrl`: Includes an extended, parsed, URL object that gives you access to Next.js specific properties such as `pathname`, `basePath`, `trailingSlash` and `i18n`. Includes the following properties:
- `basePath` (`string`)
- `buildId` (`string || undefined`)
Expand Down
26 changes: 15 additions & 11 deletions packages/next/build/webpack-config.ts
Expand Up @@ -93,7 +93,6 @@ export function getDefineEnv({
isNodeServer,
isEdgeServer,
middlewareMatchers,
hasServerComponents,
}: {
dev?: boolean
distDir: string
Expand All @@ -104,7 +103,6 @@ export function getDefineEnv({
isEdgeServer?: boolean
middlewareMatchers?: MiddlewareMatcher[]
config: NextConfigComplete
hasServerComponents?: boolean
}) {
return {
// internal field to identify the plugin config
Expand Down Expand Up @@ -178,7 +176,6 @@ export function getDefineEnv({
),
'process.env.__NEXT_STRICT_MODE': JSON.stringify(config.reactStrictMode),
'process.env.__NEXT_REACT_ROOT': JSON.stringify(hasReactRoot),
'process.env.__NEXT_RSC': JSON.stringify(hasServerComponents),
'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify(
config.optimizeFonts && !dev
),
Expand Down Expand Up @@ -540,15 +537,23 @@ export default async function getBaseWebpackConfig(
rewrites.afterFiles.length > 0 ||
rewrites.fallback.length > 0

if (isClient && !hasReactRoot) {
if (config.experimental.runtime) {
throw new Error(
'`experimental.runtime` requires React 18 to be installed.'
)
// Only error in first one compiler (client) once
if (isClient) {
if (!hasReactRoot) {
if (config.experimental.runtime) {
throw new Error(
'`experimental.runtime` requires React 18 to be installed.'
)
}
if (config.experimental.serverComponents) {
throw new Error(
'`experimental.serverComponents` requires React 18 to be installed.'
)
}
}
if (config.experimental.serverComponents) {
if (!config.experimental.appDir && config.experimental.serverComponents) {
throw new Error(
'`experimental.serverComponents` requires React 18 to be installed.'
'`experimental.serverComponents` requires experimental.appDir to be enabled.'
)
}
}
Expand Down Expand Up @@ -1680,7 +1685,6 @@ export default async function getBaseWebpackConfig(
isNodeServer,
isEdgeServer,
middlewareMatchers,
hasServerComponents,
})
),
isClient &&
Expand Down
8 changes: 5 additions & 3 deletions packages/next/client/app-index.tsx
Expand Up @@ -56,17 +56,19 @@ let initialServerDataWriter: ReadableStreamDefaultController | undefined =
let initialServerDataLoaded = false
let initialServerDataFlushed = false

function nextServerDataCallback(seg: [number, string, string]) {
function nextServerDataCallback(
seg: [isBootStrap: 0] | [isNotBootstrap: 1, responsePartial: string]
): void {
if (seg[0] === 0) {
initialServerDataBuffer = []
} else {
if (!initialServerDataBuffer)
throw new Error('Unexpected server data: missing bootstrap script.')

if (initialServerDataWriter) {
initialServerDataWriter.enqueue(encoder.encode(seg[2]))
initialServerDataWriter.enqueue(encoder.encode(seg[1]))
} else {
initialServerDataBuffer.push(seg[2])
initialServerDataBuffer.push(seg[1])
}
}
}
Expand Down

0 comments on commit 8e1c077

Please sign in to comment.