From b4042acec633bdf18175c9cc4f7905d9c757d523 Mon Sep 17 00:00:00 2001
From: Tim Neutkens <timneutkens@me.com>
Date: Tue, 29 Jun 2021 17:17:40 +0200
Subject: [PATCH 1/7] Move next-server/lib to shared/lib

Since most of these modules are shared between the client-side code and server-side code it makes more sense to move these to a "shared" directory
---
 packages/next/amp.d.ts                        |  2 +-
 packages/next/amp.js                          |  2 +-
 packages/next/bin/next.ts                     |  2 +-
 .../next/build/babel/loader/get-config.ts     |  2 +-
 packages/next/build/babel/plugins/commonjs.ts |  4 +--
 .../build/babel/plugins/next-page-config.ts   |  2 +-
 .../build/babel/plugins/next-ssg-transform.ts |  5 +---
 packages/next/build/index.ts                  |  6 ++--
 packages/next/build/utils.ts                  | 14 ++++-----
 packages/next/build/webpack-config.ts         | 21 +++++++-------
 .../webpack/loaders/next-babel-loader.js      |  4 +--
 .../loaders/next-serverless-loader/index.ts   |  4 +--
 .../next-serverless-loader/page-handler.ts    |  6 ++--
 .../loaders/next-serverless-loader/utils.ts   | 16 +++++-----
 .../webpack/plugins/build-manifest-plugin.ts  |  4 +--
 .../font-stylesheet-gathering-plugin.ts       |  2 +-
 .../plugins/next-drop-client-page-plugin.ts   |  2 +-
 .../webpack/plugins/pages-manifest-plugin.ts  |  2 +-
 packages/next/build/write-build-id.ts         |  2 +-
 packages/next/cli/next-lint.ts                |  2 +-
 packages/next/client/image.tsx                |  4 +--
 packages/next/client/index.tsx                | 29 ++++++++-----------
 packages/next/client/link.tsx                 |  2 +-
 packages/next/client/next-dev.js              |  2 +-
 packages/next/client/page-loader.ts           |  8 ++---
 packages/next/client/route-loader.ts          |  2 +-
 packages/next/client/router.ts                |  4 +--
 packages/next/client/script.tsx               |  2 +-
 packages/next/client/with-router.tsx          |  2 +-
 packages/next/config.d.ts                     |  4 +--
 packages/next/config.js                       |  2 +-
 packages/next/constants.d.ts                  |  2 +-
 packages/next/constants.js                    |  2 +-
 packages/next/dynamic.d.ts                    |  4 +--
 packages/next/dynamic.js                      |  2 +-
 packages/next/export/index.ts                 |  2 +-
 packages/next/export/worker.ts                | 12 ++++----
 packages/next/head.d.ts                       |  4 +--
 packages/next/head.js                         |  2 +-
 packages/next/lib/load-custom-routes.ts       |  2 +-
 packages/next/next-server/server/api-utils.ts |  6 +++-
 .../next-server/server/config-utils-worker.ts |  5 +++-
 .../next/next-server/server/config-utils.ts   |  2 +-
 packages/next/next-server/server/config.ts    |  7 +++--
 .../next/next-server/server/font-utils.ts     |  2 +-
 .../server/get-route-from-entrypoint.ts       |  2 +-
 .../next-server/server/incremental-cache.ts   |  2 +-
 .../next-server/server/lib/squoosh/main.ts    |  2 +-
 .../next-server/server/load-components.ts     |  7 +++--
 .../next/next-server/server/next-server.ts    | 28 ++++++++++--------
 packages/next/next-server/server/render.tsx   | 24 +++++++--------
 packages/next/next-server/server/require.ts   |  4 +--
 packages/next/next-server/server/router.ts    |  6 ++--
 .../next/next-server/server/send-payload.ts   |  2 +-
 packages/next/next-server/server/utils.ts     |  2 +-
 packages/next/pages/_app.tsx                  |  2 +-
 packages/next/pages/_document.tsx             |  6 ++--
 packages/next/pages/_error.tsx                |  4 +--
 packages/next/server/hot-reloader.ts          |  2 +-
 packages/next/server/next-dev-server.ts       |  4 +--
 packages/next/server/next.ts                  |  2 +-
 packages/next/server/static-paths-worker.ts   |  2 +-
 .../lib/amp-context.ts                        |  0
 .../next/{next-server => shared}/lib/amp.ts   |  0
 .../{next-server => shared}/lib/constants.ts  |  0
 .../lib/document-context.ts                   |  0
 .../{next-server => shared}/lib/dynamic.tsx   |  0
 .../lib/head-manager-context.ts               |  0
 .../next/{next-server => shared}/lib/head.tsx |  0
 .../lib/i18n/detect-domain-locale.ts          |  0
 .../lib/i18n/detect-locale-cookie.ts          |  0
 .../lib/i18n/normalize-locale-path.ts         |  0
 .../lib/loadable-context.ts                   |  0
 .../{next-server => shared}/lib/loadable.d.ts |  0
 .../{next-server => shared}/lib/loadable.js   |  0
 .../next/{next-server => shared}/lib/mitt.ts  |  0
 .../lib/post-process.ts                       |  0
 .../lib/router-context.ts                     |  0
 .../lib/router/router.ts                      |  4 +--
 .../router/utils/escape-path-delimiters.ts    |  0
 .../lib/router/utils/format-url.ts            |  2 +-
 .../router/utils/get-asset-path-from-route.ts |  0
 .../router/utils/get-route-from-asset-path.ts |  0
 .../lib/router/utils/index.ts                 |  0
 .../lib/router/utils/is-dynamic.ts            |  0
 .../lib/router/utils/parse-relative-url.ts    |  0
 .../lib/router/utils/path-match.ts            |  0
 .../lib/router/utils/prepare-destination.ts   |  2 +-
 .../lib/router/utils/querystring.ts           |  2 +-
 .../lib/router/utils/resolve-rewrites-noop.ts |  0
 .../lib/router/utils/resolve-rewrites.ts      |  2 +-
 .../lib/router/utils/route-matcher.ts         |  0
 .../lib/router/utils/route-regex.ts           |  0
 .../lib/router/utils/sorted-routes.ts         |  0
 .../lib/runtime-config.ts                     |  0
 .../lib/side-effect.tsx                       |  0
 .../{next-server => shared}/lib/to-base-64.ts |  0
 .../next/{next-server => shared}/lib/utils.ts |  8 ++---
 packages/next/taskfile.js                     |  9 ++++++
 packages/next/telemetry/events/version.ts     |  2 +-
 packages/next/types/index.d.ts                |  2 +-
 101 files changed, 183 insertions(+), 170 deletions(-)
 rename packages/next/{next-server => shared}/lib/amp-context.ts (100%)
 rename packages/next/{next-server => shared}/lib/amp.ts (100%)
 rename packages/next/{next-server => shared}/lib/constants.ts (100%)
 rename packages/next/{next-server => shared}/lib/document-context.ts (100%)
 rename packages/next/{next-server => shared}/lib/dynamic.tsx (100%)
 rename packages/next/{next-server => shared}/lib/head-manager-context.ts (100%)
 rename packages/next/{next-server => shared}/lib/head.tsx (100%)
 rename packages/next/{next-server => shared}/lib/i18n/detect-domain-locale.ts (100%)
 rename packages/next/{next-server => shared}/lib/i18n/detect-locale-cookie.ts (100%)
 rename packages/next/{next-server => shared}/lib/i18n/normalize-locale-path.ts (100%)
 rename packages/next/{next-server => shared}/lib/loadable-context.ts (100%)
 rename packages/next/{next-server => shared}/lib/loadable.d.ts (100%)
 rename packages/next/{next-server => shared}/lib/loadable.js (100%)
 rename packages/next/{next-server => shared}/lib/mitt.ts (100%)
 rename packages/next/{next-server => shared}/lib/post-process.ts (100%)
 rename packages/next/{next-server => shared}/lib/router-context.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/router.ts (99%)
 rename packages/next/{next-server => shared}/lib/router/utils/escape-path-delimiters.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/format-url.ts (97%)
 rename packages/next/{next-server => shared}/lib/router/utils/get-asset-path-from-route.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/get-route-from-asset-path.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/index.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/is-dynamic.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/parse-relative-url.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/path-match.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/prepare-destination.ts (99%)
 rename packages/next/{next-server => shared}/lib/router/utils/querystring.ts (95%)
 rename packages/next/{next-server => shared}/lib/router/utils/resolve-rewrites-noop.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/resolve-rewrites.ts (98%)
 rename packages/next/{next-server => shared}/lib/router/utils/route-matcher.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/route-regex.ts (100%)
 rename packages/next/{next-server => shared}/lib/router/utils/sorted-routes.ts (100%)
 rename packages/next/{next-server => shared}/lib/runtime-config.ts (100%)
 rename packages/next/{next-server => shared}/lib/side-effect.tsx (100%)
 rename packages/next/{next-server => shared}/lib/to-base-64.ts (100%)
 rename packages/next/{next-server => shared}/lib/utils.ts (98%)

diff --git a/packages/next/amp.d.ts b/packages/next/amp.d.ts
index a0c2513c93ddd..bca40393c38de 100644
--- a/packages/next/amp.d.ts
+++ b/packages/next/amp.d.ts
@@ -1 +1 @@
-export * from './dist/next-server/lib/amp'
+export * from './dist/shared/lib/amp'
diff --git a/packages/next/amp.js b/packages/next/amp.js
index dd4f3a97f4be9..9c3c257022d4b 100644
--- a/packages/next/amp.js
+++ b/packages/next/amp.js
@@ -1 +1 @@
-module.exports = require('./dist/next-server/lib/amp')
+module.exports = require('./dist/shared/lib/amp')
diff --git a/packages/next/bin/next.ts b/packages/next/bin/next.ts
index 13279f0dda78b..f74c79a158563 100755
--- a/packages/next/bin/next.ts
+++ b/packages/next/bin/next.ts
@@ -118,7 +118,7 @@ commands[command]()
   })
 
 if (command === 'dev') {
-  const { CONFIG_FILE } = require('../next-server/lib/constants')
+  const { CONFIG_FILE } = require('../shared/lib/constants')
   const { watchFile } = require('fs')
   watchFile(`${process.cwd()}/${CONFIG_FILE}`, (cur: any, prev: any) => {
     if (cur.size > 0 || prev.size > 0) {
diff --git a/packages/next/build/babel/loader/get-config.ts b/packages/next/build/babel/loader/get-config.ts
index 28623f75e8e3e..5c4855d055e78 100644
--- a/packages/next/build/babel/loader/get-config.ts
+++ b/packages/next/build/babel/loader/get-config.ts
@@ -8,7 +8,7 @@ import { NextBabelLoaderOptions, NextJsLoaderContext } from './types'
 import { consumeIterator } from './util'
 import * as Log from '../../output/log'
 
-const nextDistPath = /(next[\\/]dist[\\/]next-server[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/
+const nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/
 
 /**
  * The properties defined here are the conditions with which subsets of inputs
diff --git a/packages/next/build/babel/plugins/commonjs.ts b/packages/next/build/babel/plugins/commonjs.ts
index 2cb37a47d4039..766153450221b 100644
--- a/packages/next/build/babel/plugins/commonjs.ts
+++ b/packages/next/build/babel/plugins/commonjs.ts
@@ -1,8 +1,8 @@
 import { NodePath, PluginObj, types } from 'next/dist/compiled/babel/core'
 import commonjsPlugin from 'next/dist/compiled/babel/plugin-transform-modules-commonjs'
 
-// Rewrite imports using next/<something> to next-server/<something>
-export default function NextToNextServer(...args: any): PluginObj {
+// Handle module.exports in user code
+export default function CommonJSModulePlugin(...args: any): PluginObj {
   const commonjs = commonjsPlugin(...args)
   return {
     visitor: {
diff --git a/packages/next/build/babel/plugins/next-page-config.ts b/packages/next/build/babel/plugins/next-page-config.ts
index b6a122e6e4572..344fd440753ac 100644
--- a/packages/next/build/babel/plugins/next-page-config.ts
+++ b/packages/next/build/babel/plugins/next-page-config.ts
@@ -6,7 +6,7 @@ import {
   Visitor,
 } from 'next/dist/compiled/babel/core'
 import { PageConfig } from 'next/types'
-import { STRING_LITERAL_DROP_BUNDLE } from '../../../next-server/lib/constants'
+import { STRING_LITERAL_DROP_BUNDLE } from '../../../shared/lib/constants'
 
 const CONFIG_KEY = 'config'
 
diff --git a/packages/next/build/babel/plugins/next-ssg-transform.ts b/packages/next/build/babel/plugins/next-ssg-transform.ts
index 9439db3d55682..ba9dd130b360d 100644
--- a/packages/next/build/babel/plugins/next-ssg-transform.ts
+++ b/packages/next/build/babel/plugins/next-ssg-transform.ts
@@ -4,10 +4,7 @@ import {
   types as BabelTypes,
 } from 'next/dist/compiled/babel/core'
 import { SERVER_PROPS_SSG_CONFLICT } from '../../../lib/constants'
-import {
-  SERVER_PROPS_ID,
-  STATIC_PROPS_ID,
-} from '../../../next-server/lib/constants'
+import { SERVER_PROPS_ID, STATIC_PROPS_ID } from '../../../shared/lib/constants'
 
 export const EXPORT_NAME_GET_STATIC_PROPS = 'getStaticProps'
 export const EXPORT_NAME_GET_STATIC_PATHS = 'getStaticPaths'
diff --git a/packages/next/build/index.ts b/packages/next/build/index.ts
index 79465df567397..9c3279e5b6170 100644
--- a/packages/next/build/index.ts
+++ b/packages/next/build/index.ts
@@ -45,12 +45,12 @@ import {
   SERVER_DIRECTORY,
   SERVER_FILES_MANIFEST,
   STATIC_STATUS_PAGES,
-} from '../next-server/lib/constants'
+} from '../shared/lib/constants'
 import {
   getRouteRegex,
   getSortedRoutes,
   isDynamicRoute,
-} from '../next-server/lib/router/utils'
+} from '../shared/lib/router/utils'
 import { __ApiPreviewProps } from '../next-server/server/api-utils'
 import loadConfig, {
   isTargetLikeServerless,
@@ -89,7 +89,7 @@ import {
 import getBaseWebpackConfig from './webpack-config'
 import { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
 import { writeBuildId } from './write-build-id'
-import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path'
+import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
 import { isWebpack5 } from 'next/dist/compiled/webpack/webpack'
 
 const staticCheckWorker = require.resolve('./utils')
diff --git a/packages/next/build/utils.ts b/packages/next/build/utils.ts
index 14a00b71cdaa0..b1260a7a71ed2 100644
--- a/packages/next/build/utils.ts
+++ b/packages/next/build/utils.ts
@@ -19,16 +19,16 @@ import {
 } from '../lib/constants'
 import prettyBytes from '../lib/pretty-bytes'
 import { recursiveReadDir } from '../lib/recursive-readdir'
-import { getRouteMatcher, getRouteRegex } from '../next-server/lib/router/utils'
-import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
-import escapePathDelimiters from '../next-server/lib/router/utils/escape-path-delimiters'
+import { getRouteMatcher, getRouteRegex } from '../shared/lib/router/utils'
+import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
+import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters'
 import { findPageFile } from '../server/lib/find-page-file'
 import { GetStaticPaths } from 'next/types'
 import { denormalizePagePath } from '../next-server/server/normalize-page-path'
 import { BuildManifest } from '../next-server/server/get-page-files'
 import { removePathTrailingSlash } from '../client/normalize-trailing-slash'
 import { UnwrapPromise } from '../lib/coalesced-function'
-import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path'
+import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
 import * as Log from './output/log'
 import { loadComponents } from '../next-server/server/load-components'
 import { trace } from '../telemetry/trace'
@@ -765,7 +765,7 @@ export async function isPageStatic(
   const isPageStaticSpan = trace('is-page-static-utils', parentId)
   return isPageStaticSpan.traceAsyncFn(async () => {
     try {
-      require('../next-server/lib/runtime-config').setConfig(runtimeEnvConfig)
+      require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig)
       const components = await loadComponents(distDir, page, serverless)
       const mod = components.ComponentMod
       const Comp = mod.default || mod
@@ -880,7 +880,7 @@ export async function hasCustomGetInitialProps(
   runtimeEnvConfig: any,
   checkingApp: boolean
 ): Promise<boolean> {
-  require('../next-server/lib/runtime-config').setConfig(runtimeEnvConfig)
+  require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig)
 
   const components = await loadComponents(distDir, page, isLikeServerless)
   let mod = components.ComponentMod
@@ -900,7 +900,7 @@ export async function getNamedExports(
   isLikeServerless: boolean,
   runtimeEnvConfig: any
 ): Promise<Array<string>> {
-  require('../next-server/lib/runtime-config').setConfig(runtimeEnvConfig)
+  require('../shared/lib/runtime-config').setConfig(runtimeEnvConfig)
   const components = await loadComponents(distDir, page, isLikeServerless)
   let mod = components.ComponentMod
 
diff --git a/packages/next/build/webpack-config.ts b/packages/next/build/webpack-config.ts
index f828b86c3502f..57a2b23706b2d 100644
--- a/packages/next/build/webpack-config.ts
+++ b/packages/next/build/webpack-config.ts
@@ -25,8 +25,8 @@ import {
   REACT_LOADABLE_MANIFEST,
   SERVERLESS_DIRECTORY,
   SERVER_DIRECTORY,
-} from '../next-server/lib/constants'
-import { execOnce } from '../next-server/lib/utils'
+} from '../shared/lib/constants'
+import { execOnce } from '../shared/lib/utils'
 import { NextConfig } from '../next-server/server/config'
 import { findPageFile } from '../server/lib/find-page-file'
 import { WebpackEntrypoints } from './entries'
@@ -305,7 +305,7 @@ export default async function getBaseWebpackConfig(
   }
 
   const babelIncludeRegexes: RegExp[] = [
-    /next[\\/]dist[\\/]next-server[\\/]lib/,
+    /next[\\/]dist[\\/]shared[\\/]lib/,
     /next[\\/]dist[\\/]client/,
     /next[\\/]dist[\\/]pages/,
     /[\\/](strip-ansi|ansi-regex)[\\/]/,
@@ -396,10 +396,10 @@ export default async function getBaseWebpackConfig(
   }
 
   const clientResolveRewrites = require.resolve(
-    '../next-server/lib/router/utils/resolve-rewrites'
+    '../shared/lib/router/utils/resolve-rewrites'
   )
   const clientResolveRewritesNoop = require.resolve(
-    '../next-server/lib/router/utils/resolve-rewrites-noop'
+    '../shared/lib/router/utils/resolve-rewrites-noop'
   )
 
   const resolveConfig = {
@@ -677,6 +677,7 @@ export default async function getBaseWebpackConfig(
     // Absolute requires (require('/foo')) are extremely uncommon, but
     // also have no need for customization as they're already resolved.
     if (isLocal) {
+      // Fast bailout to ensure next-server related files don't have to be resolved
       if (!/[/\\]next-server[/\\]/.test(request)) {
         return
       }
@@ -713,9 +714,9 @@ export default async function getBaseWebpackConfig(
     }
 
     if (isLocal) {
-      // we need to process next-server/lib/router/router so that
+      // we need to process shared/lib/router/router so that
       // the DefinePlugin can inject process.env values
-      const isNextExternal = /next[/\\]dist[/\\]next-server[/\\](?!lib[/\\]router[/\\]router)/.test(
+      const isNextExternal = /next[/\\]dist[/\\]shared[/\\](?!lib[/\\]router[/\\]router)/.test(
         res
       )
 
@@ -761,9 +762,7 @@ export default async function getBaseWebpackConfig(
     }
 
     if (
-      res.match(
-        /next[/\\]dist[/\\]next-server[/\\](?!lib[/\\]router[/\\]router)/
-      )
+      res.match(/next[/\\]dist[/\\]shared[/\\](?!lib[/\\]router[/\\]router)/)
     ) {
       return `commonjs ${request}`
     }
@@ -1193,7 +1192,7 @@ export default async function getBaseWebpackConfig(
       !dev &&
         new webpack.IgnorePlugin({
           resourceRegExp: /react-is/,
-          contextRegExp: /(next-server|next)[\\/]dist[\\/]/,
+          contextRegExp: /next[\\/]dist[\\/]/,
         }),
       isServerless && isServer && new ServerlessPlugin(),
       isServer &&
diff --git a/packages/next/build/webpack/loaders/next-babel-loader.js b/packages/next/build/webpack/loaders/next-babel-loader.js
index 0aba85220043b..0633c1890a94b 100644
--- a/packages/next/build/webpack/loaders/next-babel-loader.js
+++ b/packages/next/build/webpack/loaders/next-babel-loader.js
@@ -171,12 +171,12 @@ const customBabelLoader = babelLoader((babel) => {
         }
       }
 
-      // As next-server/lib has stateful modules we have to transpile commonjs
+      // As shared/lib has stateful modules we have to transpile commonjs
       options.overrides = [
         ...(options.overrides || []),
         {
           test: [
-            /next[\\/]dist[\\/]next-server[\\/]lib/,
+            /next[\\/]dist[\\/]shared[\\/]lib/,
             /next[\\/]dist[\\/]client/,
             /next[\\/]dist[\\/]pages/,
           ],
diff --git a/packages/next/build/webpack/loaders/next-serverless-loader/index.ts b/packages/next/build/webpack/loaders/next-serverless-loader/index.ts
index 682df88d151f6..5a57643f59d2a 100644
--- a/packages/next/build/webpack/loaders/next-serverless-loader/index.ts
+++ b/packages/next/build/webpack/loaders/next-serverless-loader/index.ts
@@ -4,13 +4,13 @@ import { join } from 'path'
 import { parse } from 'querystring'
 import { webpack } from 'next/dist/compiled/webpack/webpack'
 import { API_ROUTE } from '../../../../lib/constants'
-import { isDynamicRoute } from '../../../../next-server/lib/router/utils'
+import { isDynamicRoute } from '../../../../shared/lib/router/utils'
 import { __ApiPreviewProps } from '../../../../next-server/server/api-utils'
 import {
   BUILD_MANIFEST,
   ROUTES_MANIFEST,
   REACT_LOADABLE_MANIFEST,
-} from '../../../../next-server/lib/constants'
+} from '../../../../shared/lib/constants'
 import { trace } from '../../../../telemetry/trace'
 
 export type ServerlessLoaderQuery = {
diff --git a/packages/next/build/webpack/loaders/next-serverless-loader/page-handler.ts b/packages/next/build/webpack/loaders/next-serverless-loader/page-handler.ts
index 35682cfc37225..8f9bba0f42f90 100644
--- a/packages/next/build/webpack/loaders/next-serverless-loader/page-handler.ts
+++ b/packages/next/build/webpack/loaders/next-serverless-loader/page-handler.ts
@@ -1,6 +1,6 @@
 import { IncomingMessage, ServerResponse } from 'http'
 import { parse as parseUrl, format as formatUrl, UrlWithParsedQuery } from 'url'
-import { isResSent } from '../../../../next-server/lib/utils'
+import { isResSent } from '../../../../shared/lib/utils'
 import { sendPayload } from '../../../../next-server/server/send-payload'
 import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils'
 
@@ -12,8 +12,8 @@ import {
   getCookieParser,
 } from '../../../../next-server/server/api-utils'
 import { getRedirectStatus } from '../../../../lib/load-custom-routes'
-import getRouteNoAssetPath from '../../../../next-server/lib/router/utils/get-route-from-asset-path'
-import { PERMANENT_REDIRECT_STATUS } from '../../../../next-server/lib/constants'
+import getRouteNoAssetPath from '../../../../shared/lib/router/utils/get-route-from-asset-path'
+import { PERMANENT_REDIRECT_STATUS } from '../../../../shared/lib/constants'
 
 export function getPageHandler(ctx: ServerlessHandlerCtx) {
   const {
diff --git a/packages/next/build/webpack/loaders/next-serverless-loader/utils.ts b/packages/next/build/webpack/loaders/next-serverless-loader/utils.ts
index 8845ddc110b7d..7e5342ce071c1 100644
--- a/packages/next/build/webpack/loaders/next-serverless-loader/utils.ts
+++ b/packages/next/build/webpack/loaders/next-serverless-loader/utils.ts
@@ -2,13 +2,13 @@ import { IncomingMessage, ServerResponse } from 'http'
 import { format as formatUrl, UrlWithParsedQuery, parse as parseUrl } from 'url'
 import { parse as parseQs, ParsedUrlQuery } from 'querystring'
 import { Rewrite } from '../../../../lib/load-custom-routes'
-import { normalizeLocalePath } from '../../../../next-server/lib/i18n/normalize-locale-path'
-import pathMatch from '../../../../next-server/lib/router/utils/path-match'
-import { getRouteRegex } from '../../../../next-server/lib/router/utils/route-regex'
-import { getRouteMatcher } from '../../../../next-server/lib/router/utils/route-matcher'
+import { normalizeLocalePath } from '../../../../shared/lib/i18n/normalize-locale-path'
+import pathMatch from '../../../../shared/lib/router/utils/path-match'
+import { getRouteRegex } from '../../../../shared/lib/router/utils/route-regex'
+import { getRouteMatcher } from '../../../../shared/lib/router/utils/route-matcher'
 import prepareDestination, {
   matchHas,
-} from '../../../../next-server/lib/router/utils/prepare-destination'
+} from '../../../../shared/lib/router/utils/prepare-destination'
 import { __ApiPreviewProps } from '../../../../next-server/server/api-utils'
 import { BuildManifest } from '../../../../next-server/server/get-page-files'
 import {
@@ -17,11 +17,11 @@ import {
   GetStaticProps,
 } from '../../../../types'
 import accept from '@hapi/accept'
-import { detectLocaleCookie } from '../../../../next-server/lib/i18n/detect-locale-cookie'
-import { detectDomainLocale } from '../../../../next-server/lib/i18n/detect-domain-locale'
+import { detectLocaleCookie } from '../../../../shared/lib/i18n/detect-locale-cookie'
+import { detectDomainLocale } from '../../../../shared/lib/i18n/detect-domain-locale'
 import { denormalizePagePath } from '../../../../next-server/server/denormalize-page-path'
 import cookie from 'next/dist/compiled/cookie'
-import { TEMPORARY_REDIRECT_STATUS } from '../../../../next-server/lib/constants'
+import { TEMPORARY_REDIRECT_STATUS } from '../../../../shared/lib/constants'
 import { NextConfig } from '../../../../next-server/server/config'
 
 const getCustomRouteMatcher = pathMatch(true)
diff --git a/packages/next/build/webpack/plugins/build-manifest-plugin.ts b/packages/next/build/webpack/plugins/build-manifest-plugin.ts
index fa7d7b2fbc0b0..684a15b0c7e41 100644
--- a/packages/next/build/webpack/plugins/build-manifest-plugin.ts
+++ b/packages/next/build/webpack/plugins/build-manifest-plugin.ts
@@ -11,12 +11,12 @@ import {
   CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
   CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
   CLIENT_STATIC_FILES_RUNTIME_AMP,
-} from '../../../next-server/lib/constants'
+} from '../../../shared/lib/constants'
 import { BuildManifest } from '../../../next-server/server/get-page-files'
 import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint'
 import { ampFirstEntryNamesMap } from './next-drop-client-page-plugin'
 import { Rewrite } from '../../../lib/load-custom-routes'
-import { getSortedRoutes } from '../../../next-server/lib/router/utils'
+import { getSortedRoutes } from '../../../shared/lib/router/utils'
 import { spans } from './profiling-plugin'
 import { CustomRoutes } from '../../../lib/load-custom-routes'
 
diff --git a/packages/next/build/webpack/plugins/font-stylesheet-gathering-plugin.ts b/packages/next/build/webpack/plugins/font-stylesheet-gathering-plugin.ts
index 1b7494826fb5c..05eaf32f32097 100644
--- a/packages/next/build/webpack/plugins/font-stylesheet-gathering-plugin.ts
+++ b/packages/next/build/webpack/plugins/font-stylesheet-gathering-plugin.ts
@@ -14,7 +14,7 @@ import minifier from 'cssnano-simple'
 import {
   FONT_MANIFEST,
   OPTIMIZED_FONT_PROVIDERS,
-} from '../../../next-server/lib/constants'
+} from '../../../shared/lib/constants'
 
 function minifyCss(css: string): Promise<string> {
   return postcss([
diff --git a/packages/next/build/webpack/plugins/next-drop-client-page-plugin.ts b/packages/next/build/webpack/plugins/next-drop-client-page-plugin.ts
index cb68a52bc9702..286bc1aaea6a4 100644
--- a/packages/next/build/webpack/plugins/next-drop-client-page-plugin.ts
+++ b/packages/next/build/webpack/plugins/next-drop-client-page-plugin.ts
@@ -1,6 +1,6 @@
 import { webpack } from 'next/dist/compiled/webpack/webpack'
 import { isWebpack5 } from 'next/dist/compiled/webpack/webpack'
-import { STRING_LITERAL_DROP_BUNDLE } from '../../../next-server/lib/constants'
+import { STRING_LITERAL_DROP_BUNDLE } from '../../../shared/lib/constants'
 
 export const ampFirstEntryNamesMap: WeakMap<
   webpack.compilation.Compilation,
diff --git a/packages/next/build/webpack/plugins/pages-manifest-plugin.ts b/packages/next/build/webpack/plugins/pages-manifest-plugin.ts
index 8690b95837259..aa6a02cea7759 100644
--- a/packages/next/build/webpack/plugins/pages-manifest-plugin.ts
+++ b/packages/next/build/webpack/plugins/pages-manifest-plugin.ts
@@ -3,7 +3,7 @@ import {
   isWebpack5,
   sources,
 } from 'next/dist/compiled/webpack/webpack'
-import { PAGES_MANIFEST } from '../../../next-server/lib/constants'
+import { PAGES_MANIFEST } from '../../../shared/lib/constants'
 import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint'
 
 export type PagesManifest = { [page: string]: string }
diff --git a/packages/next/build/write-build-id.ts b/packages/next/build/write-build-id.ts
index 24b84b08d51e2..1fa3a9908d5ec 100644
--- a/packages/next/build/write-build-id.ts
+++ b/packages/next/build/write-build-id.ts
@@ -1,6 +1,6 @@
 import { promises } from 'fs'
 import { join } from 'path'
-import { BUILD_ID_FILE } from '../next-server/lib/constants'
+import { BUILD_ID_FILE } from '../shared/lib/constants'
 
 export async function writeBuildId(
   distDir: string,
diff --git a/packages/next/cli/next-lint.ts b/packages/next/cli/next-lint.ts
index 57bae548524ef..15ce9d9c56b59 100755
--- a/packages/next/cli/next-lint.ts
+++ b/packages/next/cli/next-lint.ts
@@ -10,7 +10,7 @@ import { runLintCheck } from '../lib/eslint/runLintCheck'
 import { printAndExit } from '../server/lib/utils'
 import { Telemetry } from '../telemetry/storage'
 import loadConfig from '../next-server/server/config'
-import { PHASE_PRODUCTION_BUILD } from '../next-server/lib/constants'
+import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
 import { eventLintCheckCompleted } from '../telemetry/events'
 import { CompileError } from '../lib/compile-error'
 
diff --git a/packages/next/client/image.tsx b/packages/next/client/image.tsx
index e657417377e1a..362b8ce40f38a 100644
--- a/packages/next/client/image.tsx
+++ b/packages/next/client/image.tsx
@@ -1,6 +1,6 @@
 import React from 'react'
-import Head from '../next-server/lib/head'
-import { toBase64 } from '../next-server/lib/to-base-64'
+import Head from '../shared/lib/head'
+import { toBase64 } from '../shared/lib/to-base-64'
 import {
   ImageConfig,
   imageConfigDefault,
diff --git a/packages/next/client/index.tsx b/packages/next/client/index.tsx
index 32b6558c42b88..7f78aa68885f5 100644
--- a/packages/next/client/index.tsx
+++ b/packages/next/client/index.tsx
@@ -2,25 +2,20 @@
 import '@next/polyfill-module'
 import React from 'react'
 import ReactDOM from 'react-dom'
-import { HeadManagerContext } from '../next-server/lib/head-manager-context'
-import mitt, { MittEmitter } from '../next-server/lib/mitt'
-import { RouterContext } from '../next-server/lib/router-context'
+import { HeadManagerContext } from '../shared/lib/head-manager-context'
+import mitt, { MittEmitter } from '../shared/lib/mitt'
+import { RouterContext } from '../shared/lib/router-context'
 import Router, {
   AppComponent,
   AppProps,
   delBasePath,
   hasBasePath,
   PrivateRouteInfo,
-} from '../next-server/lib/router/router'
-import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
-import * as querystring from '../next-server/lib/router/utils/querystring'
-import * as envConfig from '../next-server/lib/runtime-config'
-import {
-  getURL,
-  loadGetInitialProps,
-  NEXT_DATA,
-  ST,
-} from '../next-server/lib/utils'
+} from '../shared/lib/router/router'
+import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
+import * as querystring from '../shared/lib/router/utils/querystring'
+import * as envConfig from '../shared/lib/runtime-config'
+import { getURL, loadGetInitialProps, NEXT_DATA, ST } from '../shared/lib/utils'
 import { Portal } from './portal'
 import initHeadManager from './head-manager'
 import PageLoader, { StyleSheetTuple } from './page-loader'
@@ -99,19 +94,19 @@ if (hasBasePath(asPath)) {
 if (process.env.__NEXT_I18N_SUPPORT) {
   const {
     normalizeLocalePath,
-  } = require('../next-server/lib/i18n/normalize-locale-path') as typeof import('../next-server/lib/i18n/normalize-locale-path')
+  } = require('../shared/lib/i18n/normalize-locale-path') as typeof import('../shared/lib/i18n/normalize-locale-path')
 
   const {
     detectDomainLocale,
-  } = require('../next-server/lib/i18n/detect-domain-locale') as typeof import('../next-server/lib/i18n/detect-domain-locale')
+  } = require('../shared/lib/i18n/detect-domain-locale') as typeof import('../shared/lib/i18n/detect-domain-locale')
 
   const {
     parseRelativeUrl,
-  } = require('../next-server/lib/router/utils/parse-relative-url') as typeof import('../next-server/lib/router/utils/parse-relative-url')
+  } = require('../shared/lib/router/utils/parse-relative-url') as typeof import('../shared/lib/router/utils/parse-relative-url')
 
   const {
     formatUrl,
-  } = require('../next-server/lib/router/utils/format-url') as typeof import('../next-server/lib/router/utils/format-url')
+  } = require('../shared/lib/router/utils/format-url') as typeof import('../shared/lib/router/utils/format-url')
 
   if (locales) {
     const parsedAs = parseRelativeUrl(asPath)
diff --git a/packages/next/client/link.tsx b/packages/next/client/link.tsx
index 8b4c3a762c123..b5dbd607a1bde 100644
--- a/packages/next/client/link.tsx
+++ b/packages/next/client/link.tsx
@@ -8,7 +8,7 @@ import {
   NextRouter,
   PrefetchOptions,
   resolveHref,
-} from '../next-server/lib/router/router'
+} from '../shared/lib/router/router'
 import { useRouter } from './router'
 import { useIntersection } from './use-intersection'
 
diff --git a/packages/next/client/next-dev.js b/packages/next/client/next-dev.js
index 1b2fd9a3d1916..b66e1196dd77d 100644
--- a/packages/next/client/next-dev.js
+++ b/packages/next/client/next-dev.js
@@ -6,7 +6,7 @@ import initWebpackHMR from './dev/webpack-hot-middleware-client'
 import initializeBuildWatcher from './dev/dev-build-watcher'
 import { displayContent } from './dev/fouc'
 import { addMessageListener } from './dev/error-overlay/eventsource'
-import * as querystring from '../next-server/lib/router/utils/querystring'
+import * as querystring from '../shared/lib/router/utils/querystring'
 
 // Temporary workaround for the issue described here:
 // https://github.com/vercel/next.js/issues/3775#issuecomment-407438123
diff --git a/packages/next/client/page-loader.ts b/packages/next/client/page-loader.ts
index 88fe9c427e766..e7958e228dd3d 100644
--- a/packages/next/client/page-loader.ts
+++ b/packages/next/client/page-loader.ts
@@ -4,10 +4,10 @@ import {
   addBasePath,
   addLocale,
   interpolateAs,
-} from '../next-server/lib/router/router'
-import getAssetPathFromRoute from '../next-server/lib/router/utils/get-asset-path-from-route'
-import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
-import { parseRelativeUrl } from '../next-server/lib/router/utils/parse-relative-url'
+} from '../shared/lib/router/router'
+import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route'
+import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
+import { parseRelativeUrl } from '../shared/lib/router/utils/parse-relative-url'
 import { removePathTrailingSlash } from './normalize-trailing-slash'
 import createRouteLoader, {
   getClientBuildManifest,
diff --git a/packages/next/client/route-loader.ts b/packages/next/client/route-loader.ts
index 5aa2504e9fc84..a524d16fd2b67 100644
--- a/packages/next/client/route-loader.ts
+++ b/packages/next/client/route-loader.ts
@@ -1,6 +1,6 @@
 import { ComponentType } from 'react'
 import { ClientBuildManifest } from '../build/webpack/plugins/build-manifest-plugin'
-import getAssetPathFromRoute from '../next-server/lib/router/utils/get-asset-path-from-route'
+import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route'
 import { requestIdleCallback } from './request-idle-callback'
 
 // 3.8s was arbitrarily chosen as it's what https://web.dev/interactive
diff --git a/packages/next/client/router.ts b/packages/next/client/router.ts
index b52e5e3990db2..0e7a6d0acf07f 100644
--- a/packages/next/client/router.ts
+++ b/packages/next/client/router.ts
@@ -1,7 +1,7 @@
 /* global window */
 import React from 'react'
-import Router, { NextRouter } from '../next-server/lib/router/router'
-import { RouterContext } from '../next-server/lib/router-context'
+import Router, { NextRouter } from '../shared/lib/router/router'
+import { RouterContext } from '../shared/lib/router-context'
 
 type ClassArguments<T> = T extends new (...args: infer U) => any ? U : any
 
diff --git a/packages/next/client/script.tsx b/packages/next/client/script.tsx
index 47ea97db727fc..7a6dd80922661 100644
--- a/packages/next/client/script.tsx
+++ b/packages/next/client/script.tsx
@@ -1,6 +1,6 @@
 import React, { useEffect, useContext } from 'react'
 import { ScriptHTMLAttributes } from 'react'
-import { HeadManagerContext } from '../next-server/lib/head-manager-context'
+import { HeadManagerContext } from '../shared/lib/head-manager-context'
 import { DOMAttributeNames } from './head-manager'
 import { requestIdleCallback } from './request-idle-callback'
 
diff --git a/packages/next/client/with-router.tsx b/packages/next/client/with-router.tsx
index 217a65bd15c1d..194053a7fc526 100644
--- a/packages/next/client/with-router.tsx
+++ b/packages/next/client/with-router.tsx
@@ -1,5 +1,5 @@
 import React from 'react'
-import { NextComponentType, NextPageContext } from '../next-server/lib/utils'
+import { NextComponentType, NextPageContext } from '../shared/lib/utils'
 import { NextRouter, useRouter } from './router'
 
 export type WithRouterProps = {
diff --git a/packages/next/config.d.ts b/packages/next/config.d.ts
index 8393fd1db7f78..89aaf61357cf2 100644
--- a/packages/next/config.d.ts
+++ b/packages/next/config.d.ts
@@ -1,2 +1,2 @@
-export * from './dist/next-server/lib/runtime-config'
-export { default } from './dist/next-server/lib/runtime-config'
+export * from './dist/shared/lib/runtime-config'
+export { default } from './dist/shared/lib/runtime-config'
diff --git a/packages/next/config.js b/packages/next/config.js
index 2091b30008eb7..2da980d8b0065 100644
--- a/packages/next/config.js
+++ b/packages/next/config.js
@@ -1 +1 @@
-module.exports = require('./dist/next-server/lib/runtime-config')
+module.exports = require('./dist/shared/lib/runtime-config')
diff --git a/packages/next/constants.d.ts b/packages/next/constants.d.ts
index 9bcdbe336dda4..11c676af75a83 100644
--- a/packages/next/constants.d.ts
+++ b/packages/next/constants.d.ts
@@ -1 +1 @@
-export * from './dist/next-server/lib/constants'
+export * from './dist/shared/lib/constants'
diff --git a/packages/next/constants.js b/packages/next/constants.js
index b194c55634d84..6e690109937c5 100644
--- a/packages/next/constants.js
+++ b/packages/next/constants.js
@@ -1 +1 @@
-module.exports = require('./dist/next-server/lib/constants')
+module.exports = require('./dist/shared/lib/constants')
diff --git a/packages/next/dynamic.d.ts b/packages/next/dynamic.d.ts
index 0b5640d913ff6..bc3003f5c9bc5 100644
--- a/packages/next/dynamic.d.ts
+++ b/packages/next/dynamic.d.ts
@@ -1,2 +1,2 @@
-export * from './dist/next-server/lib/dynamic'
-export { default } from './dist/next-server/lib/dynamic'
+export * from './dist/shared/lib/dynamic'
+export { default } from './dist/shared/lib/dynamic'
diff --git a/packages/next/dynamic.js b/packages/next/dynamic.js
index b844a69abc19b..e2956e5f40337 100644
--- a/packages/next/dynamic.js
+++ b/packages/next/dynamic.js
@@ -1 +1 @@
-module.exports = require('./dist/next-server/lib/dynamic')
+module.exports = require('./dist/shared/lib/dynamic')
diff --git a/packages/next/export/index.ts b/packages/next/export/index.ts
index 54a8bf54b38da..0ffe2f7af9acb 100644
--- a/packages/next/export/index.ts
+++ b/packages/next/export/index.ts
@@ -28,7 +28,7 @@ import {
   PRERENDER_MANIFEST,
   SERVERLESS_DIRECTORY,
   SERVER_DIRECTORY,
-} from '../next-server/lib/constants'
+} from '../shared/lib/constants'
 import loadConfig, {
   isTargetLikeServerless,
   NextConfig,
diff --git a/packages/next/export/worker.ts b/packages/next/export/worker.ts
index 057c4c5f1ebd5..cf8cea79065d4 100644
--- a/packages/next/export/worker.ts
+++ b/packages/next/export/worker.ts
@@ -4,9 +4,9 @@ import { renderToHTML } from '../next-server/server/render'
 import { promises } from 'fs'
 import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
 import { loadComponents } from '../next-server/server/load-components'
-import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
-import { getRouteMatcher } from '../next-server/lib/router/utils/route-matcher'
-import { getRouteRegex } from '../next-server/lib/router/utils/route-regex'
+import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
+import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
+import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
 import { normalizePagePath } from '../next-server/server/normalize-page-path'
 import { SERVER_PROPS_EXPORT_ERROR } from '../lib/constants'
 import 'next/dist/next-server/server/node-polyfill-fetch'
@@ -15,11 +15,11 @@ import { ComponentType } from 'react'
 import { GetStaticProps } from '../types'
 import { requireFontManifest } from '../next-server/server/require'
 import { FontManifest } from '../next-server/server/font-utils'
-import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path'
+import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
 import { trace } from '../telemetry/trace'
-import { isInAmpMode } from '../next-server/lib/amp'
+import { isInAmpMode } from '../shared/lib/amp'
 
-const envConfig = require('../next-server/lib/runtime-config')
+const envConfig = require('../shared/lib/runtime-config')
 
 ;(global as any).__NEXT_DATA__ = {
   nextExport: true,
diff --git a/packages/next/head.d.ts b/packages/next/head.d.ts
index 9f0379787712d..24a9a99a1f1d1 100644
--- a/packages/next/head.d.ts
+++ b/packages/next/head.d.ts
@@ -1,2 +1,2 @@
-export * from './dist/next-server/lib/head'
-export { default } from './dist/next-server/lib/head'
+export * from './dist/shared/lib/head'
+export { default } from './dist/shared/lib/head'
diff --git a/packages/next/head.js b/packages/next/head.js
index ca344986dc48a..71758fdbeaa5c 100644
--- a/packages/next/head.js
+++ b/packages/next/head.js
@@ -1 +1 @@
-module.exports = require('./dist/next-server/lib/head')
+module.exports = require('./dist/shared/lib/head')
diff --git a/packages/next/lib/load-custom-routes.ts b/packages/next/lib/load-custom-routes.ts
index ca6e98344dfad..09e4cee073c1a 100644
--- a/packages/next/lib/load-custom-routes.ts
+++ b/packages/next/lib/load-custom-routes.ts
@@ -5,7 +5,7 @@ import escapeStringRegexp from 'next/dist/compiled/escape-string-regexp'
 import {
   PERMANENT_REDIRECT_STATUS,
   TEMPORARY_REDIRECT_STATUS,
-} from '../next-server/lib/constants'
+} from '../shared/lib/constants'
 
 export type RouteHas =
   | {
diff --git a/packages/next/next-server/server/api-utils.ts b/packages/next/next-server/server/api-utils.ts
index 350a87dac212f..ea20b683eacc7 100644
--- a/packages/next/next-server/server/api-utils.ts
+++ b/packages/next/next-server/server/api-utils.ts
@@ -4,7 +4,11 @@ import { CookieSerializeOptions } from 'next/dist/compiled/cookie'
 import getRawBody from 'raw-body'
 import { PageConfig, PreviewData } from 'next/types'
 import { Stream } from 'stream'
-import { isResSent, NextApiRequest, NextApiResponse } from '../lib/utils'
+import {
+  isResSent,
+  NextApiRequest,
+  NextApiResponse,
+} from '../../shared/lib/utils'
 import { decryptWithSecret, encryptWithSecret } from './crypto-utils'
 import { interopDefault } from './load-components'
 import { sendEtagResponse } from './send-payload'
diff --git a/packages/next/next-server/server/config-utils-worker.ts b/packages/next/next-server/server/config-utils-worker.ts
index 3842f0e34a054..02d4a83d9d905 100644
--- a/packages/next/next-server/server/config-utils-worker.ts
+++ b/packages/next/next-server/server/config-utils-worker.ts
@@ -1,7 +1,10 @@
 import { loadEnvConfig } from '@next/env'
 import findUp from 'next/dist/compiled/find-up'
 import { init as initWebpack } from 'next/dist/compiled/webpack/webpack'
-import { CONFIG_FILE, PHASE_DEVELOPMENT_SERVER } from '../lib/constants'
+import {
+  CONFIG_FILE,
+  PHASE_DEVELOPMENT_SERVER,
+} from '../../shared/lib/constants'
 import { NextConfig, normalizeConfig } from './config-shared'
 import * as Log from '../../build/output/log'
 
diff --git a/packages/next/next-server/server/config-utils.ts b/packages/next/next-server/server/config-utils.ts
index 36aa99cba830e..107032394edc3 100644
--- a/packages/next/next-server/server/config-utils.ts
+++ b/packages/next/next-server/server/config-utils.ts
@@ -3,7 +3,7 @@ import { Worker } from 'jest-worker'
 import * as Log from '../../build/output/log'
 import { CheckReasons, CheckResult } from './config-utils-worker'
 import { install, shouldLoadWithWebpack5 } from './config-utils-worker'
-import { PHASE_PRODUCTION_SERVER } from '../lib/constants'
+import { PHASE_PRODUCTION_SERVER } from '../../shared/lib/constants'
 
 export { install, shouldLoadWithWebpack5 }
 
diff --git a/packages/next/next-server/server/config.ts b/packages/next/next-server/server/config.ts
index beeb39de5a9fc..7b49d8a6d37bd 100644
--- a/packages/next/next-server/server/config.ts
+++ b/packages/next/next-server/server/config.ts
@@ -3,8 +3,11 @@ import findUp from 'next/dist/compiled/find-up'
 import { basename, extname } from 'path'
 import * as Log from '../../build/output/log'
 import { hasNextSupport } from '../../telemetry/ci-info'
-import { CONFIG_FILE, PHASE_DEVELOPMENT_SERVER } from '../lib/constants'
-import { execOnce } from '../lib/utils'
+import {
+  CONFIG_FILE,
+  PHASE_DEVELOPMENT_SERVER,
+} from '../../shared/lib/constants'
+import { execOnce } from '../../shared/lib/utils'
 import { defaultConfig, normalizeConfig } from './config-shared'
 import { loadWebpackHook } from './config-utils'
 import { ImageConfig, imageConfigDefault, VALID_LOADERS } from './image-config'
diff --git a/packages/next/next-server/server/font-utils.ts b/packages/next/next-server/server/font-utils.ts
index 6e2b9cfee6a3a..db5de03a294a1 100644
--- a/packages/next/next-server/server/font-utils.ts
+++ b/packages/next/next-server/server/font-utils.ts
@@ -1,5 +1,5 @@
 import * as Log from '../../build/output/log'
-import { GOOGLE_FONT_PROVIDER } from '../lib/constants'
+import { GOOGLE_FONT_PROVIDER } from '../../shared/lib/constants'
 const https = require('https')
 
 const CHROME_UA =
diff --git a/packages/next/next-server/server/get-route-from-entrypoint.ts b/packages/next/next-server/server/get-route-from-entrypoint.ts
index 0e082cfd51dc9..48da52f6e31ed 100644
--- a/packages/next/next-server/server/get-route-from-entrypoint.ts
+++ b/packages/next/next-server/server/get-route-from-entrypoint.ts
@@ -1,4 +1,4 @@
-import getRouteFromAssetPath from '../lib/router/utils/get-route-from-asset-path'
+import getRouteFromAssetPath from '../../shared/lib/router/utils/get-route-from-asset-path'
 
 // matches pages/:page*.js
 const SERVER_ROUTE_NAME_REGEX = /^pages[/\\](.*)$/
diff --git a/packages/next/next-server/server/incremental-cache.ts b/packages/next/next-server/server/incremental-cache.ts
index cd9b08cbe72a7..32ad4d63b1cb1 100644
--- a/packages/next/next-server/server/incremental-cache.ts
+++ b/packages/next/next-server/server/incremental-cache.ts
@@ -2,7 +2,7 @@ import { promises, readFileSync } from 'fs'
 import LRUCache from 'next/dist/compiled/lru-cache'
 import path from 'path'
 import { PrerenderManifest } from '../../build'
-import { PRERENDER_MANIFEST } from '../lib/constants'
+import { PRERENDER_MANIFEST } from '../../shared/lib/constants'
 import { normalizePagePath } from './normalize-page-path'
 
 function toRoute(pathname: string): string {
diff --git a/packages/next/next-server/server/lib/squoosh/main.ts b/packages/next/next-server/server/lib/squoosh/main.ts
index 4b885764481ab..3e81a335cd9b8 100644
--- a/packages/next/next-server/server/lib/squoosh/main.ts
+++ b/packages/next/next-server/server/lib/squoosh/main.ts
@@ -1,6 +1,6 @@
 import { Worker } from 'jest-worker'
 import * as path from 'path'
-import { execOnce } from '../../../lib/utils'
+import { execOnce } from '../../../../shared/lib/utils'
 import { cpus } from 'os'
 
 type RotateOperation = {
diff --git a/packages/next/next-server/server/load-components.ts b/packages/next/next-server/server/load-components.ts
index 14ad0a11170f5..d828d53756559 100644
--- a/packages/next/next-server/server/load-components.ts
+++ b/packages/next/next-server/server/load-components.ts
@@ -1,8 +1,11 @@
-import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST } from '../lib/constants'
+import {
+  BUILD_MANIFEST,
+  REACT_LOADABLE_MANIFEST,
+} from '../../shared/lib/constants'
 import { join } from 'path'
 import { requirePage } from './require'
 import { BuildManifest } from './get-page-files'
-import { AppType, DocumentType } from '../lib/utils'
+import { AppType, DocumentType } from '../../shared/lib/utils'
 import {
   PageConfig,
   GetStaticPaths,
diff --git a/packages/next/next-server/server/next-server.ts b/packages/next/next-server/server/next-server.ts
index 4a57fa059a878..c697f4a914138 100644
--- a/packages/next/next-server/server/next-server.ts
+++ b/packages/next/next-server/server/next-server.ts
@@ -33,15 +33,19 @@ import {
   SERVER_DIRECTORY,
   STATIC_STATUS_PAGES,
   TEMPORARY_REDIRECT_STATUS,
-} from '../lib/constants'
+} from '../../shared/lib/constants'
 import {
   getRouteMatcher,
   getRouteRegex,
   getSortedRoutes,
   isDynamicRoute,
-} from '../lib/router/utils'
-import * as envConfig from '../lib/runtime-config'
-import { isResSent, NextApiRequest, NextApiResponse } from '../lib/utils'
+} from '../../shared/lib/router/utils'
+import * as envConfig from '../../shared/lib/runtime-config'
+import {
+  isResSent,
+  NextApiRequest,
+  NextApiResponse,
+} from '../../shared/lib/utils'
 import {
   apiResolver,
   setLazyProp,
@@ -50,7 +54,7 @@ import {
   __ApiPreviewProps,
 } from './api-utils'
 import { DomainLocales, isTargetLikeServerless, NextConfig } from './config'
-import pathMatch from '../lib/router/utils/path-match'
+import pathMatch from '../../shared/lib/router/utils/path-match'
 import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
 import {
   loadComponents,
@@ -69,27 +73,27 @@ import Router, {
 } from './router'
 import prepareDestination, {
   compileNonPath,
-} from '../lib/router/utils/prepare-destination'
+} from '../../shared/lib/router/utils/prepare-destination'
 import { sendPayload, setRevalidateHeaders } from './send-payload'
 import { serveStatic } from './serve-static'
 import { IncrementalCache } from './incremental-cache'
-import { execOnce } from '../lib/utils'
+import { execOnce } from '../../shared/lib/utils'
 import { isBlockedPage } from './utils'
 import { loadEnvConfig } from '@next/env'
 import './node-polyfill-fetch'
 import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
 import { removePathTrailingSlash } from '../../client/normalize-trailing-slash'
-import getRouteFromAssetPath from '../lib/router/utils/get-route-from-asset-path'
+import getRouteFromAssetPath from '../../shared/lib/router/utils/get-route-from-asset-path'
 import { FontManifest } from './font-utils'
 import { denormalizePagePath } from './denormalize-page-path'
 import accept from '@hapi/accept'
-import { normalizeLocalePath } from '../lib/i18n/normalize-locale-path'
-import { detectLocaleCookie } from '../lib/i18n/detect-locale-cookie'
+import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
+import { detectLocaleCookie } from '../../shared/lib/i18n/detect-locale-cookie'
 import * as Log from '../../build/output/log'
 import { imageOptimizer } from './image-optimizer'
-import { detectDomainLocale } from '../lib/i18n/detect-domain-locale'
+import { detectDomainLocale } from '../../shared/lib/i18n/detect-domain-locale'
 import cookie from 'next/dist/compiled/cookie'
-import escapePathDelimiters from '../lib/router/utils/escape-path-delimiters'
+import escapePathDelimiters from '../../shared/lib/router/utils/escape-path-delimiters'
 import { getUtils } from '../../build/webpack/loaders/next-serverless-loader/utils'
 import { PreviewData } from 'next/types'
 import HotReloader from '../../server/hot-reloader'
diff --git a/packages/next/next-server/server/render.tsx b/packages/next/next-server/server/render.tsx
index b94331a95fff5..380b08201c260 100644
--- a/packages/next/next-server/server/render.tsx
+++ b/packages/next/next-server/server/render.tsx
@@ -16,22 +16,22 @@ import {
 } from '../../lib/constants'
 import { isSerializableProps } from '../../lib/is-serializable-props'
 import { GetServerSideProps, GetStaticProps, PreviewData } from '../../types'
-import { isInAmpMode } from '../lib/amp'
-import { AmpStateContext } from '../lib/amp-context'
+import { isInAmpMode } from '../../shared/lib/amp'
+import { AmpStateContext } from '../../shared/lib/amp-context'
 import {
   AMP_RENDER_TARGET,
   SERVER_PROPS_ID,
   STATIC_PROPS_ID,
   STATIC_STATUS_PAGES,
-} from '../lib/constants'
-import { defaultHead } from '../lib/head'
-import { HeadManagerContext } from '../lib/head-manager-context'
-import Loadable from '../lib/loadable'
-import { LoadableContext } from '../lib/loadable-context'
-import postProcess from '../lib/post-process'
-import { RouterContext } from '../lib/router-context'
-import { NextRouter } from '../lib/router/router'
-import { isDynamicRoute } from '../lib/router/utils/is-dynamic'
+} from '../../shared/lib/constants'
+import { defaultHead } from '../../shared/lib/head'
+import { HeadManagerContext } from '../../shared/lib/head-manager-context'
+import Loadable from '../../shared/lib/loadable'
+import { LoadableContext } from '../../shared/lib/loadable-context'
+import postProcess from '../../shared/lib/post-process'
+import { RouterContext } from '../../shared/lib/router-context'
+import { NextRouter } from '../../shared/lib/router/router'
+import { isDynamicRoute } from '../../shared/lib/router/utils/is-dynamic'
 import {
   AppType,
   ComponentsEnhancer,
@@ -43,7 +43,7 @@ import {
   loadGetInitialProps,
   NextComponentType,
   RenderPage,
-} from '../lib/utils'
+} from '../../shared/lib/utils'
 import {
   tryGetPreviewData,
   NextApiRequestCookies,
diff --git a/packages/next/next-server/server/require.ts b/packages/next/next-server/server/require.ts
index 7c079332a58a7..4fdeb2db94ee7 100644
--- a/packages/next/next-server/server/require.ts
+++ b/packages/next/next-server/server/require.ts
@@ -5,10 +5,10 @@ import {
   SERVER_DIRECTORY,
   SERVERLESS_DIRECTORY,
   FONT_MANIFEST,
-} from '../lib/constants'
+} from '../../shared/lib/constants'
 import { normalizePagePath, denormalizePagePath } from './normalize-page-path'
 import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
-import { normalizeLocalePath } from '../lib/i18n/normalize-locale-path'
+import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
 
 export function pageNotFoundError(page: string): Error {
   const err: any = new Error(`Cannot find module for page: ${page}`)
diff --git a/packages/next/next-server/server/router.ts b/packages/next/next-server/server/router.ts
index 5c0f437ea267e..61439c780b7a8 100644
--- a/packages/next/next-server/server/router.ts
+++ b/packages/next/next-server/server/router.ts
@@ -1,11 +1,11 @@
 import { IncomingMessage, ServerResponse } from 'http'
 import { UrlWithParsedQuery } from 'url'
 
-import pathMatch from '../lib/router/utils/path-match'
+import pathMatch from '../../shared/lib/router/utils/path-match'
 import { removePathTrailingSlash } from '../../client/normalize-trailing-slash'
-import { normalizeLocalePath } from '../lib/i18n/normalize-locale-path'
+import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
 import { RouteHas } from '../../lib/load-custom-routes'
-import { matchHas } from '../lib/router/utils/prepare-destination'
+import { matchHas } from '../../shared/lib/router/utils/prepare-destination'
 
 export const route = pathMatch()
 
diff --git a/packages/next/next-server/server/send-payload.ts b/packages/next/next-server/server/send-payload.ts
index 400e4c210fa3b..a29512605b438 100644
--- a/packages/next/next-server/server/send-payload.ts
+++ b/packages/next/next-server/server/send-payload.ts
@@ -1,5 +1,5 @@
 import { IncomingMessage, ServerResponse } from 'http'
-import { isResSent } from '../lib/utils'
+import { isResSent } from '../../shared/lib/utils'
 import generateETag from 'etag'
 import fresh from 'next/dist/compiled/fresh'
 
diff --git a/packages/next/next-server/server/utils.ts b/packages/next/next-server/server/utils.ts
index 4f26da01625a0..e3753127ce26c 100644
--- a/packages/next/next-server/server/utils.ts
+++ b/packages/next/next-server/server/utils.ts
@@ -1,4 +1,4 @@
-import { BLOCKED_PAGES } from '../lib/constants'
+import { BLOCKED_PAGES } from '../../shared/lib/constants'
 
 export function isBlockedPage(pathname: string): boolean {
   return BLOCKED_PAGES.includes(pathname)
diff --git a/packages/next/pages/_app.tsx b/packages/next/pages/_app.tsx
index 4036cfd89674e..334a34b4a306e 100644
--- a/packages/next/pages/_app.tsx
+++ b/packages/next/pages/_app.tsx
@@ -5,7 +5,7 @@ import {
   AppInitialProps,
   AppPropsType,
   NextWebVitalsMetric,
-} from '../next-server/lib/utils'
+} from '../shared/lib/utils'
 import { Router } from '../client/router'
 
 export { AppInitialProps }
diff --git a/packages/next/pages/_document.tsx b/packages/next/pages/_document.tsx
index 57d95097eea19..168a856e89f90 100644
--- a/packages/next/pages/_document.tsx
+++ b/packages/next/pages/_document.tsx
@@ -4,13 +4,13 @@ import flush from 'styled-jsx/server'
 import {
   AMP_RENDER_TARGET,
   OPTIMIZED_FONT_PROVIDERS,
-} from '../next-server/lib/constants'
-import { DocumentContext as DocumentComponentContext } from '../next-server/lib/document-context'
+} from '../shared/lib/constants'
+import { DocumentContext as DocumentComponentContext } from '../shared/lib/document-context'
 import {
   DocumentContext,
   DocumentInitialProps,
   DocumentProps,
-} from '../next-server/lib/utils'
+} from '../shared/lib/utils'
 import {
   BuildManifest,
   getPageFiles,
diff --git a/packages/next/pages/_error.tsx b/packages/next/pages/_error.tsx
index c2cec6217d23a..7038c221216bf 100644
--- a/packages/next/pages/_error.tsx
+++ b/packages/next/pages/_error.tsx
@@ -1,6 +1,6 @@
 import React from 'react'
-import Head from '../next-server/lib/head'
-import { NextPageContext } from '../next-server/lib/utils'
+import Head from '../shared/lib/head'
+import { NextPageContext } from '../shared/lib/utils'
 
 const statusCodes: { [code: number]: string } = {
   400: 'Bad Request',
diff --git a/packages/next/server/hot-reloader.ts b/packages/next/server/hot-reloader.ts
index ab91b544ae0b3..f46875e829224 100644
--- a/packages/next/server/hot-reloader.ts
+++ b/packages/next/server/hot-reloader.ts
@@ -10,7 +10,7 @@ import { watchCompilers } from '../build/output'
 import getBaseWebpackConfig from '../build/webpack-config'
 import { API_ROUTE } from '../lib/constants'
 import { recursiveDelete } from '../lib/recursive-delete'
-import { BLOCKED_PAGES } from '../next-server/lib/constants'
+import { BLOCKED_PAGES } from '../shared/lib/constants'
 import { __ApiPreviewProps } from '../next-server/server/api-utils'
 import { route } from '../next-server/server/router'
 import { findPageFile } from './lib/find-page-file'
diff --git a/packages/next/server/next-dev-server.ts b/packages/next/server/next-dev-server.ts
index 6919bfb8f94bd..1eb062e20f738 100644
--- a/packages/next/server/next-dev-server.ts
+++ b/packages/next/server/next-dev-server.ts
@@ -20,13 +20,13 @@ import {
   CLIENT_STATIC_FILES_PATH,
   DEV_CLIENT_PAGES_MANIFEST,
   STATIC_STATUS_PAGES,
-} from '../next-server/lib/constants'
+} from '../shared/lib/constants'
 import {
   getRouteMatcher,
   getRouteRegex,
   getSortedRoutes,
   isDynamicRoute,
-} from '../next-server/lib/router/utils'
+} from '../shared/lib/router/utils'
 import { __ApiPreviewProps } from '../next-server/server/api-utils'
 import Server, { ServerConstructor } from '../next-server/server/next-server'
 import { normalizePagePath } from '../next-server/server/normalize-page-path'
diff --git a/packages/next/server/next.ts b/packages/next/server/next.ts
index 6af1dfe57bcc1..4eba61bca4b2f 100644
--- a/packages/next/server/next.ts
+++ b/packages/next/server/next.ts
@@ -10,7 +10,7 @@ import { resolve } from 'path'
 import {
   PHASE_DEVELOPMENT_SERVER,
   PHASE_PRODUCTION_SERVER,
-} from '../next-server/lib/constants'
+} from '../shared/lib/constants'
 import { IncomingMessage, ServerResponse } from 'http'
 import { UrlWithParsedQuery } from 'url'
 
diff --git a/packages/next/server/static-paths-worker.ts b/packages/next/server/static-paths-worker.ts
index ffd2e02866c01..78200786e0ead 100644
--- a/packages/next/server/static-paths-worker.ts
+++ b/packages/next/server/static-paths-worker.ts
@@ -24,7 +24,7 @@ export async function loadStaticPaths(
   }
 
   // update work memory runtime-config
-  require('./../next-server/lib/runtime-config').setConfig(config)
+  require('../shared/lib/runtime-config').setConfig(config)
 
   const components = await loadComponents(distDir, pathname, serverless)
 
diff --git a/packages/next/next-server/lib/amp-context.ts b/packages/next/shared/lib/amp-context.ts
similarity index 100%
rename from packages/next/next-server/lib/amp-context.ts
rename to packages/next/shared/lib/amp-context.ts
diff --git a/packages/next/next-server/lib/amp.ts b/packages/next/shared/lib/amp.ts
similarity index 100%
rename from packages/next/next-server/lib/amp.ts
rename to packages/next/shared/lib/amp.ts
diff --git a/packages/next/next-server/lib/constants.ts b/packages/next/shared/lib/constants.ts
similarity index 100%
rename from packages/next/next-server/lib/constants.ts
rename to packages/next/shared/lib/constants.ts
diff --git a/packages/next/next-server/lib/document-context.ts b/packages/next/shared/lib/document-context.ts
similarity index 100%
rename from packages/next/next-server/lib/document-context.ts
rename to packages/next/shared/lib/document-context.ts
diff --git a/packages/next/next-server/lib/dynamic.tsx b/packages/next/shared/lib/dynamic.tsx
similarity index 100%
rename from packages/next/next-server/lib/dynamic.tsx
rename to packages/next/shared/lib/dynamic.tsx
diff --git a/packages/next/next-server/lib/head-manager-context.ts b/packages/next/shared/lib/head-manager-context.ts
similarity index 100%
rename from packages/next/next-server/lib/head-manager-context.ts
rename to packages/next/shared/lib/head-manager-context.ts
diff --git a/packages/next/next-server/lib/head.tsx b/packages/next/shared/lib/head.tsx
similarity index 100%
rename from packages/next/next-server/lib/head.tsx
rename to packages/next/shared/lib/head.tsx
diff --git a/packages/next/next-server/lib/i18n/detect-domain-locale.ts b/packages/next/shared/lib/i18n/detect-domain-locale.ts
similarity index 100%
rename from packages/next/next-server/lib/i18n/detect-domain-locale.ts
rename to packages/next/shared/lib/i18n/detect-domain-locale.ts
diff --git a/packages/next/next-server/lib/i18n/detect-locale-cookie.ts b/packages/next/shared/lib/i18n/detect-locale-cookie.ts
similarity index 100%
rename from packages/next/next-server/lib/i18n/detect-locale-cookie.ts
rename to packages/next/shared/lib/i18n/detect-locale-cookie.ts
diff --git a/packages/next/next-server/lib/i18n/normalize-locale-path.ts b/packages/next/shared/lib/i18n/normalize-locale-path.ts
similarity index 100%
rename from packages/next/next-server/lib/i18n/normalize-locale-path.ts
rename to packages/next/shared/lib/i18n/normalize-locale-path.ts
diff --git a/packages/next/next-server/lib/loadable-context.ts b/packages/next/shared/lib/loadable-context.ts
similarity index 100%
rename from packages/next/next-server/lib/loadable-context.ts
rename to packages/next/shared/lib/loadable-context.ts
diff --git a/packages/next/next-server/lib/loadable.d.ts b/packages/next/shared/lib/loadable.d.ts
similarity index 100%
rename from packages/next/next-server/lib/loadable.d.ts
rename to packages/next/shared/lib/loadable.d.ts
diff --git a/packages/next/next-server/lib/loadable.js b/packages/next/shared/lib/loadable.js
similarity index 100%
rename from packages/next/next-server/lib/loadable.js
rename to packages/next/shared/lib/loadable.js
diff --git a/packages/next/next-server/lib/mitt.ts b/packages/next/shared/lib/mitt.ts
similarity index 100%
rename from packages/next/next-server/lib/mitt.ts
rename to packages/next/shared/lib/mitt.ts
diff --git a/packages/next/next-server/lib/post-process.ts b/packages/next/shared/lib/post-process.ts
similarity index 100%
rename from packages/next/next-server/lib/post-process.ts
rename to packages/next/shared/lib/post-process.ts
diff --git a/packages/next/next-server/lib/router-context.ts b/packages/next/shared/lib/router-context.ts
similarity index 100%
rename from packages/next/next-server/lib/router-context.ts
rename to packages/next/shared/lib/router-context.ts
diff --git a/packages/next/next-server/lib/router/router.ts b/packages/next/shared/lib/router/router.ts
similarity index 99%
rename from packages/next/next-server/lib/router/router.ts
rename to packages/next/shared/lib/router/router.ts
index 0e348a4c0e7f3..c3e69847ac424 100644
--- a/packages/next/next-server/lib/router/router.ts
+++ b/packages/next/shared/lib/router/router.ts
@@ -13,8 +13,8 @@ import {
   markAssetError,
 } from '../../../client/route-loader'
 import { RouterEvent } from '../../../client/router'
-import { DomainLocales } from '../../server/config'
-import { denormalizePagePath } from '../../server/denormalize-page-path'
+import { DomainLocales } from '../../../next-server/server/config'
+import { denormalizePagePath } from '../../../next-server/server/denormalize-page-path'
 import { normalizeLocalePath } from '../i18n/normalize-locale-path'
 import mitt, { MittEmitter } from '../mitt'
 import {
diff --git a/packages/next/next-server/lib/router/utils/escape-path-delimiters.ts b/packages/next/shared/lib/router/utils/escape-path-delimiters.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/escape-path-delimiters.ts
rename to packages/next/shared/lib/router/utils/escape-path-delimiters.ts
diff --git a/packages/next/next-server/lib/router/utils/format-url.ts b/packages/next/shared/lib/router/utils/format-url.ts
similarity index 97%
rename from packages/next/next-server/lib/router/utils/format-url.ts
rename to packages/next/shared/lib/router/utils/format-url.ts
index bef24b4e3e7d3..90629d56ac20a 100644
--- a/packages/next/next-server/lib/router/utils/format-url.ts
+++ b/packages/next/shared/lib/router/utils/format-url.ts
@@ -21,7 +21,7 @@
 // USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 import { UrlObject } from 'url'
-import { ParsedUrlQuery } from 'querystring'
+import { ParsedUrlQuery } from 'shared/lib/router/utils/querystring'
 import * as querystring from './querystring'
 
 const slashedProtocols = /https?|ftp|gopher|file/
diff --git a/packages/next/next-server/lib/router/utils/get-asset-path-from-route.ts b/packages/next/shared/lib/router/utils/get-asset-path-from-route.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/get-asset-path-from-route.ts
rename to packages/next/shared/lib/router/utils/get-asset-path-from-route.ts
diff --git a/packages/next/next-server/lib/router/utils/get-route-from-asset-path.ts b/packages/next/shared/lib/router/utils/get-route-from-asset-path.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/get-route-from-asset-path.ts
rename to packages/next/shared/lib/router/utils/get-route-from-asset-path.ts
diff --git a/packages/next/next-server/lib/router/utils/index.ts b/packages/next/shared/lib/router/utils/index.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/index.ts
rename to packages/next/shared/lib/router/utils/index.ts
diff --git a/packages/next/next-server/lib/router/utils/is-dynamic.ts b/packages/next/shared/lib/router/utils/is-dynamic.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/is-dynamic.ts
rename to packages/next/shared/lib/router/utils/is-dynamic.ts
diff --git a/packages/next/next-server/lib/router/utils/parse-relative-url.ts b/packages/next/shared/lib/router/utils/parse-relative-url.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/parse-relative-url.ts
rename to packages/next/shared/lib/router/utils/parse-relative-url.ts
diff --git a/packages/next/next-server/lib/router/utils/path-match.ts b/packages/next/shared/lib/router/utils/path-match.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/path-match.ts
rename to packages/next/shared/lib/router/utils/path-match.ts
diff --git a/packages/next/next-server/lib/router/utils/prepare-destination.ts b/packages/next/shared/lib/router/utils/prepare-destination.ts
similarity index 99%
rename from packages/next/next-server/lib/router/utils/prepare-destination.ts
rename to packages/next/shared/lib/router/utils/prepare-destination.ts
index 4fbb4430eea69..a6937032dfa47 100644
--- a/packages/next/next-server/lib/router/utils/prepare-destination.ts
+++ b/packages/next/shared/lib/router/utils/prepare-destination.ts
@@ -1,5 +1,5 @@
 import { IncomingMessage } from 'http'
-import { ParsedUrlQuery } from 'querystring'
+import { ParsedUrlQuery } from 'shared/lib/router/utils/querystring'
 import { searchParamsToUrlQuery } from './querystring'
 import { parseRelativeUrl } from './parse-relative-url'
 import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
diff --git a/packages/next/next-server/lib/router/utils/querystring.ts b/packages/next/shared/lib/router/utils/querystring.ts
similarity index 95%
rename from packages/next/next-server/lib/router/utils/querystring.ts
rename to packages/next/shared/lib/router/utils/querystring.ts
index f86d7a3c257e6..550cd98dd9835 100644
--- a/packages/next/next-server/lib/router/utils/querystring.ts
+++ b/packages/next/shared/lib/router/utils/querystring.ts
@@ -1,4 +1,4 @@
-import { ParsedUrlQuery } from 'querystring'
+import { ParsedUrlQuery } from 'shared/lib/router/utils/querystring'
 
 export function searchParamsToUrlQuery(
   searchParams: URLSearchParams
diff --git a/packages/next/next-server/lib/router/utils/resolve-rewrites-noop.ts b/packages/next/shared/lib/router/utils/resolve-rewrites-noop.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/resolve-rewrites-noop.ts
rename to packages/next/shared/lib/router/utils/resolve-rewrites-noop.ts
diff --git a/packages/next/next-server/lib/router/utils/resolve-rewrites.ts b/packages/next/shared/lib/router/utils/resolve-rewrites.ts
similarity index 98%
rename from packages/next/next-server/lib/router/utils/resolve-rewrites.ts
rename to packages/next/shared/lib/router/utils/resolve-rewrites.ts
index b6551862abffc..7f934ea1140b8 100644
--- a/packages/next/next-server/lib/router/utils/resolve-rewrites.ts
+++ b/packages/next/shared/lib/router/utils/resolve-rewrites.ts
@@ -1,4 +1,4 @@
-import { ParsedUrlQuery } from 'querystring'
+import { ParsedUrlQuery } from 'shared/lib/router/utils/querystring'
 import pathMatch from './path-match'
 import prepareDestination, { matchHas } from './prepare-destination'
 import { Rewrite } from '../../../../lib/load-custom-routes'
diff --git a/packages/next/next-server/lib/router/utils/route-matcher.ts b/packages/next/shared/lib/router/utils/route-matcher.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/route-matcher.ts
rename to packages/next/shared/lib/router/utils/route-matcher.ts
diff --git a/packages/next/next-server/lib/router/utils/route-regex.ts b/packages/next/shared/lib/router/utils/route-regex.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/route-regex.ts
rename to packages/next/shared/lib/router/utils/route-regex.ts
diff --git a/packages/next/next-server/lib/router/utils/sorted-routes.ts b/packages/next/shared/lib/router/utils/sorted-routes.ts
similarity index 100%
rename from packages/next/next-server/lib/router/utils/sorted-routes.ts
rename to packages/next/shared/lib/router/utils/sorted-routes.ts
diff --git a/packages/next/next-server/lib/runtime-config.ts b/packages/next/shared/lib/runtime-config.ts
similarity index 100%
rename from packages/next/next-server/lib/runtime-config.ts
rename to packages/next/shared/lib/runtime-config.ts
diff --git a/packages/next/next-server/lib/side-effect.tsx b/packages/next/shared/lib/side-effect.tsx
similarity index 100%
rename from packages/next/next-server/lib/side-effect.tsx
rename to packages/next/shared/lib/side-effect.tsx
diff --git a/packages/next/next-server/lib/to-base-64.ts b/packages/next/shared/lib/to-base-64.ts
similarity index 100%
rename from packages/next/next-server/lib/to-base-64.ts
rename to packages/next/shared/lib/to-base-64.ts
diff --git a/packages/next/next-server/lib/utils.ts b/packages/next/shared/lib/utils.ts
similarity index 98%
rename from packages/next/next-server/lib/utils.ts
rename to packages/next/shared/lib/utils.ts
index 36adb6359eb33..dd0fb11050e61 100644
--- a/packages/next/next-server/lib/utils.ts
+++ b/packages/next/shared/lib/utils.ts
@@ -5,14 +5,10 @@ import { UrlObject } from 'url'
 import { formatUrl } from './router/utils/format-url'
 import { NextRouter } from './router/router'
 import { Env } from '@next/env'
-import { BuildManifest } from '../server/get-page-files'
-import { DomainLocales } from '../server/config'
+import { BuildManifest } from '../../next-server/server/get-page-files'
+import { DomainLocales } from '../../next-server/server/config'
 import { PreviewData } from 'next/types'
 
-/**
- * Types used by both next and next-server
- */
-
 export type NextComponentType<
   C extends BaseContext = NextPageContext,
   IP = {},
diff --git a/packages/next/taskfile.js b/packages/next/taskfile.js
index 97189e4676e04..fde6f472b0df3 100644
--- a/packages/next/taskfile.js
+++ b/packages/next/taskfile.js
@@ -926,6 +926,7 @@ export default async function (task) {
   await task.watch('cli/**/*.+(js|ts|tsx)', 'cli', opts)
   await task.watch('telemetry/**/*.+(js|ts|tsx)', 'telemetry', opts)
   await task.watch('next-server/**/*.+(js|ts|tsx)', 'nextserver', opts)
+  await task.watch('shared/**/*.+(js|ts|tsx)', 'shared', opts)
   await task.watch('next-server/**/*.+(wasm)', 'nextserver_wasm', opts)
 }
 
@@ -937,6 +938,14 @@ export async function nextserver(task, opts) {
   notify('Compiled server files')
 }
 
+export async function shared(task, opts) {
+  await task
+    .source(opts.src || 'shared/**/*.+(js|ts|tsx)')
+    .babel('server', { dev: opts.dev })
+    .target('dist/shared')
+  notify('Compiled shared files')
+}
+
 export async function nextserver_wasm(task, opts) {
   await task
     .source(opts.src || 'next-server/**/*.+(wasm)')
diff --git a/packages/next/telemetry/events/version.ts b/packages/next/telemetry/events/version.ts
index c05675e08d6b8..155419d57f8ff 100644
--- a/packages/next/telemetry/events/version.ts
+++ b/packages/next/telemetry/events/version.ts
@@ -5,7 +5,7 @@ import {
   PHASE_DEVELOPMENT_SERVER,
   PHASE_EXPORT,
   PHASE_PRODUCTION_BUILD,
-} from '../../next-server/lib/constants'
+} from '../../shared/lib/constants'
 import { normalizeConfig } from '../../next-server/server/config'
 
 const EVENT_VERSION = 'NEXT_CLI_SESSION_STARTED'
diff --git a/packages/next/types/index.d.ts b/packages/next/types/index.d.ts
index 476d491ed7f65..cb9d59442b249 100644
--- a/packages/next/types/index.d.ts
+++ b/packages/next/types/index.d.ts
@@ -13,7 +13,7 @@ import {
   NextApiRequest,
   NextApiHandler,
   // @ts-ignore This path is generated at build time and conflicts otherwise
-} from '../dist/next-server/lib/utils'
+} from '../dist/shared/lib/utils'
 
 import {
   NextApiRequestCookies,

From a9ff9383fdb4d791609ff2eefd9570ed1583f3b9 Mon Sep 17 00:00:00 2001
From: Tim Neutkens <timneutkens@me.com>
Date: Tue, 29 Jun 2021 17:19:49 +0200
Subject: [PATCH 2/7] Remove bailout as there's no bundling part of next-server
 anymore

---
 packages/next/build/webpack-config.ts | 7 +------
 1 file changed, 1 insertion(+), 6 deletions(-)

diff --git a/packages/next/build/webpack-config.ts b/packages/next/build/webpack-config.ts
index 57a2b23706b2d..c518f3da8b969 100644
--- a/packages/next/build/webpack-config.ts
+++ b/packages/next/build/webpack-config.ts
@@ -676,12 +676,7 @@ export default async function getBaseWebpackConfig(
     // are relative to requests we've already resolved here.
     // Absolute requires (require('/foo')) are extremely uncommon, but
     // also have no need for customization as they're already resolved.
-    if (isLocal) {
-      // Fast bailout to ensure next-server related files don't have to be resolved
-      if (!/[/\\]next-server[/\\]/.test(request)) {
-        return
-      }
-    } else {
+    if (!isLocal) {
       if (/^(?:next$|react(?:$|\/))/.test(request)) {
         return `commonjs ${request}`
       }

From 70539eebcadf4bbee25e7127aa870d13c0d730e2 Mon Sep 17 00:00:00 2001
From: Tim Neutkens <timneutkens@me.com>
Date: Tue, 29 Jun 2021 17:38:11 +0200
Subject: [PATCH 3/7] Add shared to initial compile

---
 packages/next/taskfile.js | 1 +
 1 file changed, 1 insertion(+)

diff --git a/packages/next/taskfile.js b/packages/next/taskfile.js
index fde6f472b0df3..810bcfb34d01d 100644
--- a/packages/next/taskfile.js
+++ b/packages/next/taskfile.js
@@ -809,6 +809,7 @@ export async function compile(task, opts) {
       'client',
       'telemetry',
       'nextserver',
+      'shared',
       'nextserver_wasm',
       // we compile this each time so that fresh runtime data is pulled
       // before each publish

From 8937333e7b7c212d64e74e9138f4fdd965bff00b Mon Sep 17 00:00:00 2001
From: Tim Neutkens <timneutkens@me.com>
Date: Tue, 29 Jun 2021 17:55:48 +0200
Subject: [PATCH 4/7] Fix incorrectly changed webstorm refactor

---
 packages/next/shared/lib/router/utils/format-url.ts          | 2 +-
 packages/next/shared/lib/router/utils/prepare-destination.ts | 2 +-
 packages/next/shared/lib/router/utils/querystring.ts         | 2 +-
 packages/next/shared/lib/router/utils/resolve-rewrites.ts    | 2 +-
 4 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/packages/next/shared/lib/router/utils/format-url.ts b/packages/next/shared/lib/router/utils/format-url.ts
index 90629d56ac20a..bef24b4e3e7d3 100644
--- a/packages/next/shared/lib/router/utils/format-url.ts
+++ b/packages/next/shared/lib/router/utils/format-url.ts
@@ -21,7 +21,7 @@
 // USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 import { UrlObject } from 'url'
-import { ParsedUrlQuery } from 'shared/lib/router/utils/querystring'
+import { ParsedUrlQuery } from 'querystring'
 import * as querystring from './querystring'
 
 const slashedProtocols = /https?|ftp|gopher|file/
diff --git a/packages/next/shared/lib/router/utils/prepare-destination.ts b/packages/next/shared/lib/router/utils/prepare-destination.ts
index a6937032dfa47..4fbb4430eea69 100644
--- a/packages/next/shared/lib/router/utils/prepare-destination.ts
+++ b/packages/next/shared/lib/router/utils/prepare-destination.ts
@@ -1,5 +1,5 @@
 import { IncomingMessage } from 'http'
-import { ParsedUrlQuery } from 'shared/lib/router/utils/querystring'
+import { ParsedUrlQuery } from 'querystring'
 import { searchParamsToUrlQuery } from './querystring'
 import { parseRelativeUrl } from './parse-relative-url'
 import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
diff --git a/packages/next/shared/lib/router/utils/querystring.ts b/packages/next/shared/lib/router/utils/querystring.ts
index 550cd98dd9835..f86d7a3c257e6 100644
--- a/packages/next/shared/lib/router/utils/querystring.ts
+++ b/packages/next/shared/lib/router/utils/querystring.ts
@@ -1,4 +1,4 @@
-import { ParsedUrlQuery } from 'shared/lib/router/utils/querystring'
+import { ParsedUrlQuery } from 'querystring'
 
 export function searchParamsToUrlQuery(
   searchParams: URLSearchParams
diff --git a/packages/next/shared/lib/router/utils/resolve-rewrites.ts b/packages/next/shared/lib/router/utils/resolve-rewrites.ts
index 7f934ea1140b8..b6551862abffc 100644
--- a/packages/next/shared/lib/router/utils/resolve-rewrites.ts
+++ b/packages/next/shared/lib/router/utils/resolve-rewrites.ts
@@ -1,4 +1,4 @@
-import { ParsedUrlQuery } from 'shared/lib/router/utils/querystring'
+import { ParsedUrlQuery } from 'querystring'
 import pathMatch from './path-match'
 import prepareDestination, { matchHas } from './prepare-destination'
 import { Rewrite } from '../../../../lib/load-custom-routes'

From c927ae9345869d19332ad4f42c9f7d83263e6918 Mon Sep 17 00:00:00 2001
From: Tim Neutkens <timneutkens@me.com>
Date: Tue, 29 Jun 2021 21:27:40 +0200
Subject: [PATCH 5/7] Update dist/next-server/lib to dist/shared/lib in tests

---
 test/integration/externalize-next-server/test/index.test.js | 6 +++---
 test/integration/getserversideprops/pages/index.js          | 2 +-
 test/unit/getDisplayName.unit.test.js                       | 2 +-
 test/unit/loadGetInitialProps.unit.test.js                  | 2 +-
 test/unit/mitt.unit.test.js                                 | 2 +-
 test/unit/page-route-sorter.unit.test.js                    | 2 +-
 test/unit/parse-relative-url.unit.test.js                   | 2 +-
 test/unit/router-add-base-path.unit.test.js                 | 2 +-
 8 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/test/integration/externalize-next-server/test/index.test.js b/test/integration/externalize-next-server/test/index.test.js
index a50d4f86df60e..0fffff8cf367b 100644
--- a/test/integration/externalize-next-server/test/index.test.js
+++ b/test/integration/externalize-next-server/test/index.test.js
@@ -7,18 +7,18 @@ jest.setTimeout(1000 * 60 * 1)
 
 const appDir = path.join(__dirname, '../app')
 
-describe('externalize next/dist/next-server', () => {
+describe('externalize next/dist/shared', () => {
   beforeAll(async () => {
     await nextBuild(appDir)
   })
 
-  it('Does not bundle next/dist/next-server/lib/head.js in _error', async () => {
+  it('Does not bundle next/dist/shared/lib/head.js in _error', async () => {
     const content = readNextBuildServerPageFile(appDir, '/_error')
     expect(content).toMatch(
       new RegExp(
         '^' +
           escapeStringRegexp(
-            `module.exports = require("next/dist/next-server/lib/head.js");`
+            `module.exports = require("next/dist/shared/lib/head.js");`
           ) +
           ';?$',
         'm'
diff --git a/test/integration/getserversideprops/pages/index.js b/test/integration/getserversideprops/pages/index.js
index 8bbf910a94dcd..ecd88bda1a811 100644
--- a/test/integration/getserversideprops/pages/index.js
+++ b/test/integration/getserversideprops/pages/index.js
@@ -1,6 +1,6 @@
 import Link from 'next/link'
 import ReactDOM from 'react-dom/server'
-import { RouterContext } from 'next/dist/next-server/lib/router-context'
+import { RouterContext } from 'next/dist/shared/lib/router-context'
 import { useRouter } from 'next/router'
 
 function RouterComp(props) {
diff --git a/test/unit/getDisplayName.unit.test.js b/test/unit/getDisplayName.unit.test.js
index 1c14fe336aea5..974d0e3001474 100644
--- a/test/unit/getDisplayName.unit.test.js
+++ b/test/unit/getDisplayName.unit.test.js
@@ -1,6 +1,6 @@
 /* eslint-env jest */
 import { Component } from 'react'
-import { getDisplayName } from 'next/dist/next-server/lib/utils'
+import { getDisplayName } from 'next/dist/shared/lib/utils'
 
 describe('getDisplayName', () => {
   it('gets the proper display name of a component', () => {
diff --git a/test/unit/loadGetInitialProps.unit.test.js b/test/unit/loadGetInitialProps.unit.test.js
index bb9e59797d131..8f7a42690bfcb 100644
--- a/test/unit/loadGetInitialProps.unit.test.js
+++ b/test/unit/loadGetInitialProps.unit.test.js
@@ -1,5 +1,5 @@
 /* eslint-env jest */
-import { loadGetInitialProps } from 'next/dist/next-server/lib/utils'
+import { loadGetInitialProps } from 'next/dist/shared/lib/utils'
 
 describe('loadGetInitialProps', () => {
   it('should throw if getInitialProps is defined as an instance method', () => {
diff --git a/test/unit/mitt.unit.test.js b/test/unit/mitt.unit.test.js
index 79e3a7bb541b0..541f3dc49fc7b 100644
--- a/test/unit/mitt.unit.test.js
+++ b/test/unit/mitt.unit.test.js
@@ -1,5 +1,5 @@
 /* eslint-env jest */
-import mitt from 'next/dist/next-server/lib/mitt'
+import mitt from 'next/dist/shared/lib/mitt'
 
 describe('mitt', () => {
   describe('With listeners', () => {
diff --git a/test/unit/page-route-sorter.unit.test.js b/test/unit/page-route-sorter.unit.test.js
index 2fc6a4c6c1014..a97375a09a8e8 100644
--- a/test/unit/page-route-sorter.unit.test.js
+++ b/test/unit/page-route-sorter.unit.test.js
@@ -1,5 +1,5 @@
 /* eslint-env jest */
-import { getSortedRoutes } from 'next/dist/next-server/lib/router/utils/sorted-routes'
+import { getSortedRoutes } from 'next/dist/shared/lib/router/utils/sorted-routes'
 
 describe('getSortedRoutes', () => {
   it('does not add extra routes', () => {
diff --git a/test/unit/parse-relative-url.unit.test.js b/test/unit/parse-relative-url.unit.test.js
index ed6a312a127f3..3d1097ecb23ef 100644
--- a/test/unit/parse-relative-url.unit.test.js
+++ b/test/unit/parse-relative-url.unit.test.js
@@ -1,5 +1,5 @@
 /* eslint-env jest */
-import { parseRelativeUrl } from 'next/dist/next-server/lib/router/utils/parse-relative-url'
+import { parseRelativeUrl } from 'next/dist/shared/lib/router/utils/parse-relative-url'
 
 // convenience function so tests can be aligned neatly
 // and easy to eyeball
diff --git a/test/unit/router-add-base-path.unit.test.js b/test/unit/router-add-base-path.unit.test.js
index ab308dd20f578..027492343a028 100644
--- a/test/unit/router-add-base-path.unit.test.js
+++ b/test/unit/router-add-base-path.unit.test.js
@@ -1,5 +1,5 @@
 /* eslint-env jest */
-import { addBasePath } from 'next/dist/next-server/lib/router/router'
+import { addBasePath } from 'next/dist/shared/lib/router/router'
 
 describe('router addBasePath', () => {
   it('should add basePath correctly when no basePath', () => {

From de0b3a343d61bee2f170ef218e80114005da529c Mon Sep 17 00:00:00 2001
From: Tim Neutkens <timneutkens@me.com>
Date: Wed, 30 Jun 2021 09:29:05 +0200
Subject: [PATCH 6/7] Escape dot in test regex

---
 .../getserversideprops-export-error/test/index.test.js          | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/test/integration/getserversideprops-export-error/test/index.test.js b/test/integration/getserversideprops-export-error/test/index.test.js
index c079330fe1bd7..c716584807905 100644
--- a/test/integration/getserversideprops-export-error/test/index.test.js
+++ b/test/integration/getserversideprops-export-error/test/index.test.js
@@ -24,7 +24,7 @@ const runTests = () => {
 
     expect(code).toBe(1)
     expect(stderr).toMatch(
-      /pages with `getServerSideProps` can not be exported. See more info here: https/
+      /pages with `getServerSideProps` can not be exported\. See more info here: https/
     )
   })
 }

From cfaad3f2e53734ad20680ec7105f4034294e6694 Mon Sep 17 00:00:00 2001
From: Tim Neutkens <timneutkens@me.com>
Date: Wed, 30 Jun 2021 09:49:41 +0200
Subject: [PATCH 7/7] Ensure dist/next-server and dist/shared are not bundled

---
 packages/next/build/webpack-config.ts | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/packages/next/build/webpack-config.ts b/packages/next/build/webpack-config.ts
index c518f3da8b969..b1986a6defc1a 100644
--- a/packages/next/build/webpack-config.ts
+++ b/packages/next/build/webpack-config.ts
@@ -709,9 +709,10 @@ export default async function getBaseWebpackConfig(
     }
 
     if (isLocal) {
+      // Makes sure dist/shared and dist/next-server are not bundled
       // we need to process shared/lib/router/router so that
       // the DefinePlugin can inject process.env values
-      const isNextExternal = /next[/\\]dist[/\\]shared[/\\](?!lib[/\\]router[/\\]router)/.test(
+      const isNextExternal = /next[/\\]dist[/\\](shared|next-server)[/\\](?!lib[/\\]router[/\\]router)/.test(
         res
       )