Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Keep custom app as non server component #37044

Merged
merged 8 commits into from
May 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 1 addition & 9 deletions docs/advanced-features/react-18/server-components.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,7 @@ export default function Document() {

### `next/app`

If you're using `_app.js`, the usage is the same as [Custom App](/docs/advanced-features/custom-app).
If you're using `_app.server.js` as a server component, see the example below where it only receives the `children` prop as React elements. You can wrap any other client or server components around `children` to customize the layout of your app.

```js
// pages/_app.server.js
export default function App({ children }) {
return children
}
```
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.
huozhi marked this conversation as resolved.
Show resolved Hide resolved

### Routing

Expand Down
16 changes: 3 additions & 13 deletions packages/next/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,20 @@ import {
import { __ApiPreviewProps } from '../server/api-utils'
import { isTargetLikeServerless } from '../server/utils'
import { warn } from './output/log'
import { isServerComponentPage } from './utils'
import { getPageStaticInfo } from './analysis/get-page-static-info'
import { isServerComponentPage, withoutRSCExtensions } from './utils'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { serverComponentRegex } from './webpack/loaders/utils'

type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never

/**
* For a given page path removes the provided extensions. `/_app.server` is a
* special case because it is the only page where we want to preserve the RSC
* server extension.
* For a given page path removes the provided extensions.
*/
export function getPageFromPath(pagePath: string, pageExtensions: string[]) {
const extensions = pagePath.includes('/_app.server.')
? withoutRSCExtensions(pageExtensions)
: pageExtensions

let page = normalizePathSep(
pagePath.replace(new RegExp(`\\.+(${extensions.join('|')})$`), '')
pagePath.replace(new RegExp(`\\.+(${pageExtensions.join('|')})$`), '')
)

page = page.replace(/\/index$/, '')
Expand Down Expand Up @@ -118,7 +112,6 @@ export function createPagesMapping({

if (isDev) {
delete pages['/_app']
delete pages['/_app.server']
delete pages['/_error']
delete pages['/_document']
}
Expand All @@ -132,7 +125,6 @@ export function createPagesMapping({
'/_app': `${root}/_app`,
'/_error': `${root}/_error`,
'/_document': `${root}/_document`,
...(hasServerComponents ? { '/_app.server': `${root}/_app.server` } : {}),
...pages,
}
}
Expand Down Expand Up @@ -175,7 +167,6 @@ export function getEdgeServerEntry(opts: {
const loaderParams: MiddlewareSSRLoaderQuery = {
absolute500Path: opts.pages['/500'] || '',
absoluteAppPath: opts.pages['/_app'],
absoluteAppServerPath: opts.pages['/_app.server'],
absoluteDocumentPath: opts.pages['/_document'],
absoluteErrorPath: opts.pages['/_error'],
absolutePagePath: opts.absolutePagePath,
Expand Down Expand Up @@ -219,7 +210,6 @@ export function getServerlessEntry(opts: {
const loaderParams: ServerlessLoaderQuery = {
absolute404Path: opts.pages['/404'] || '',
absoluteAppPath: opts.pages['/_app'],
absoluteAppServerPath: opts.pages['/_app.server'],
absoluteDocumentPath: opts.pages['/_document'],
absoluteErrorPath: opts.pages['/_error'],
absolutePagePath: opts.absolutePagePath,
Expand Down
9 changes: 1 addition & 8 deletions packages/next/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,12 +141,6 @@ export async function printTreeView(
]

const hasCustomApp = await findPageFile(pagesDir, '/_app', pageExtensions)
const hasCustomAppServer = await findPageFile(
pagesDir,
'/_app.server',
pageExtensions
)

pageInfos.set('/404', {
...(pageInfos.get('/404') || pageInfos.get('/_error')),
static: useStatic404,
Expand All @@ -172,8 +166,7 @@ export async function printTreeView(
!(
e === '/_document' ||
e === '/_error' ||
(!hasCustomApp && e === '/_app') ||
(!hasCustomAppServer && e === '/_app.server')
(!hasCustomApp && e === '/_app')
)
)
.sort((a, b) => a.localeCompare(b))
Expand Down
9 changes: 1 addition & 8 deletions packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,19 +606,12 @@ export default async function getBaseWebpackConfig(

if (dev) {
customAppAliases[`${PAGES_DIR_ALIAS}/_app`] = [
...rawPageExtensions.reduce((prev, ext) => {
...config.pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_app.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/_app.js',
]
customAppAliases[`${PAGES_DIR_ALIAS}/_app.server`] = [
...rawPageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_app.server.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/_app.server.js',
]
customAppAliases[`${PAGES_DIR_ALIAS}/_error`] = [
...config.pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_error.${ext}`))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { stringifyRequest } from '../../stringify-request'
export type MiddlewareSSRLoaderQuery = {
absolute500Path: string
absoluteAppPath: string
absoluteAppServerPath: string
absoluteDocumentPath: string
absoluteErrorPath: string
absolutePagePath: string
Expand All @@ -22,7 +21,6 @@ export default async function middlewareSSRLoader(this: any) {
buildId,
absolutePagePath,
absoluteAppPath,
absoluteAppServerPath,
absoluteDocumentPath,
absolute500Path,
absoluteErrorPath,
Expand All @@ -42,10 +40,6 @@ export default async function middlewareSSRLoader(this: any) {

const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAppPath = stringifyRequest(this, absoluteAppPath)
const stringifiedAppServerPath = absoluteAppServerPath
? stringifyRequest(this, absoluteAppServerPath)
: null

const stringifiedErrorPath = stringifyRequest(this, absoluteErrorPath)
const stringifiedDocumentPath = stringifyRequest(this, absoluteDocumentPath)
const stringified500Path = absolute500Path
Expand All @@ -61,9 +55,6 @@ export default async function middlewareSSRLoader(this: any) {
import Document from ${stringifiedDocumentPath}

const appMod = require(${stringifiedAppPath})
const appServerMod = ${
stringifiedAppServerPath ? `require(${stringifiedAppServerPath})` : 'null'
}
const pageMod = require(${stringifiedPagePath})
const errorMod = require(${stringifiedErrorPath})
const error500Mod = ${
Expand All @@ -85,7 +76,6 @@ export default async function middlewareSSRLoader(this: any) {
buildManifest,
reactLoadableManifest,
serverComponentManifest: ${isServerComponent} ? rscManifest : null,
appServerMod,
config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)},
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ export function getRender({
serverComponentManifest,
config,
buildId,
appServerMod,
}: {
dev: boolean
page: string
Expand All @@ -49,8 +48,6 @@ export function getRender({
reactLoadableManifest,
Document,
App: appMod.default as AppType,
AppMod: appMod,
AppServerMod: appServerMod,
}

const server = new WebServer({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export type ServerlessLoaderQuery = {
distDir: string
absolutePagePath: string
absoluteAppPath: string
absoluteAppServerPath: string
absoluteDocumentPath: string
absoluteErrorPath: string
absolute404Path: string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
_params?: any
) {
let Component
let AppMod
let App
let config
let Document
let Error
Expand All @@ -78,7 +78,7 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
getServerSideProps,
getStaticPaths,
Component,
AppMod,
App,
config,
{ default: Document },
{ default: Error },
Expand All @@ -103,7 +103,7 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
setLazyProp({ req: req as any }, 'cookies', getCookieParser(req.headers))

const options = {
AppMod,
App,
Document,
ComponentMod: { default: Component },
buildManifest,
Expand Down
2 changes: 0 additions & 2 deletions packages/next/build/webpack/plugins/flight-manifest-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,6 @@ export class FlightManifestPlugin {
// For each SC server compilation entry, we need to create its corresponding
// client component entry.
for (const [name, entry] of compilation.entries.entries()) {
if (name === 'pages/_app.server') continue

// Check if the page entry is a server component or not.
const entryDependency = entry.dependencies?.[0]
const request = entryDependency?.request
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export default class PagesManifestPlugin implements webpack.Plugin {
file.endsWith('.js')
)

// Skip _app.server entry which is empty
// Skip entries which are empty
if (!files.length) {
continue
}
Expand Down
9 changes: 1 addition & 8 deletions packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ let webpackHMR: any

let CachedApp: AppComponent, onPerfEntry: (metric: any) => void
let CachedComponent: React.ComponentType
let isRSCPage: boolean

class Container extends React.Component<{
fn: (err: Error, info?: any) => void
Expand Down Expand Up @@ -331,7 +330,6 @@ export async function hydrate(opts?: { beforeRender?: () => Promise<void> }) {
throw pageEntrypoint.error
}
CachedComponent = pageEntrypoint.component
isRSCPage = !!pageEntrypoint.exports.__next_rsc__

if (process.env.NODE_ENV !== 'production') {
const { isValidElementType } = require('next/dist/compiled/react-is')
Expand Down Expand Up @@ -647,12 +645,7 @@ function AppContainer({
}

function renderApp(App: AppComponent, appProps: AppProps) {
if (process.env.__NEXT_RSC && isRSCPage) {
const { Component, err: _, router: __, ...props } = appProps
return <Component {...props} />
} else {
return <App {...appProps} />
}
return <App {...appProps} />
}

const wrapApp =
Expand Down
7 changes: 1 addition & 6 deletions packages/next/export/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,12 +237,7 @@ export default async function exportApp(
continue
}

if (
page === '/_document' ||
page === '/_app.server' ||
page === '/_app' ||
page === '/_error'
) {
if (page === '/_document' || page === '/_app' || page === '/_error') {
continue
}

Expand Down
3 changes: 0 additions & 3 deletions packages/next/pages/_app.server.tsx

This file was deleted.

14 changes: 1 addition & 13 deletions packages/next/server/load-components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ export type LoadComponentsReturnType = {
getStaticPaths?: GetStaticPaths
getServerSideProps?: GetServerSideProps
ComponentMod: any
AppMod: any
AppServerMod: any
isViewPath?: boolean
}

Expand All @@ -60,9 +58,6 @@ export async function loadDefaultErrorComponents(distDir: string) {
buildManifest: require(join(distDir, `fallback-${BUILD_MANIFEST}`)),
reactLoadableManifest: {},
ComponentMod,
AppMod,
// Use App for fallback
AppServerMod: AppMod,
}
}

Expand Down Expand Up @@ -106,7 +101,7 @@ export async function loadComponents(
} as LoadComponentsReturnType
}

const [DocumentMod, AppMod, ComponentMod, AppServerMod] = await Promise.all([
const [DocumentMod, AppMod, ComponentMod] = await Promise.all([
Promise.resolve().then(() =>
requirePage('/_document', distDir, serverless, rootEnabled)
),
Expand All @@ -116,11 +111,6 @@ export async function loadComponents(
Promise.resolve().then(() =>
requirePage(pathname, distDir, serverless, rootEnabled)
),
hasServerComponents
? Promise.resolve().then(() =>
requirePage('/_app.server', distDir, serverless, rootEnabled)
)
: null,
])

const [buildManifest, reactLoadableManifest, serverComponentManifest] =
Expand Down Expand Up @@ -175,8 +165,6 @@ export async function loadComponents(
reactLoadableManifest,
pageConfig: ComponentMod.config || {},
ComponentMod,
AppMod,
AppServerMod,
getServerSideProps,
getStaticProps,
getStaticPaths,
Expand Down
Loading