-
Notifications
You must be signed in to change notification settings - Fork 27.8k
/
Copy pathrouter.ts
2394 lines (2117 loc) · 68.8 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// tslint:disable:no-console
import type { ComponentType } from 'react'
import type { DomainLocale } from '../../../server/config'
import type { MittEmitter } from '../mitt'
import type { ParsedUrlQuery } from 'querystring'
import type { RouterEvent } from '../../../client/router'
import type { StyleSheetTuple } from '../../../client/page-loader'
import type { UrlObject } from 'url'
import type PageLoader from '../../../client/page-loader'
import { normalizePathTrailingSlash } from '../../../client/normalize-trailing-slash'
import { removeTrailingSlash } from './utils/remove-trailing-slash'
import {
getClientBuildManifest,
isAssetError,
markAssetError,
} from '../../../client/route-loader'
import { handleClientScriptLoad } from '../../../client/script'
import isError, { getProperError } from '../../../lib/is-error'
import { denormalizePagePath } from '../page-path/denormalize-page-path'
import { normalizeLocalePath } from '../i18n/normalize-locale-path'
import mitt from '../mitt'
import {
AppContextType,
getLocationOrigin,
getURL,
loadGetInitialProps,
normalizeRepeatedSlashes,
NextPageContext,
ST,
NEXT_DATA,
isAbsoluteUrl,
} from '../utils'
import { isDynamicRoute } from './utils/is-dynamic'
import { parseRelativeUrl } from './utils/parse-relative-url'
import { searchParamsToUrlQuery } from './utils/querystring'
import resolveRewrites from './utils/resolve-rewrites'
import { getRouteMatcher } from './utils/route-matcher'
import { getRouteRegex } from './utils/route-regex'
import { formatWithValidation } from './utils/format-url'
import { detectDomainLocale } from '../../../client/detect-domain-locale'
import { parsePath } from './utils/parse-path'
import { addLocale } from '../../../client/add-locale'
import { removeLocale } from '../../../client/remove-locale'
import { removeBasePath } from '../../../client/remove-base-path'
import { addBasePath } from '../../../client/add-base-path'
import { hasBasePath } from '../../../client/has-base-path'
import { getNextPathnameInfo } from './utils/get-next-pathname-info'
import { formatNextPathnameInfo } from './utils/format-next-pathname-info'
declare global {
interface Window {
/* prod */
__NEXT_DATA__: NEXT_DATA
}
}
interface RouteProperties {
shallow: boolean
}
interface TransitionOptions {
shallow?: boolean
locale?: string | false
scroll?: boolean
unstable_skipClientCache?: boolean
}
interface NextHistoryState {
url: string
as: string
options: TransitionOptions
}
export type HistoryState =
| null
| { __N: false }
| ({ __N: true; key: string } & NextHistoryState)
function buildCancellationError() {
return Object.assign(new Error('Route Cancelled'), {
cancelled: true,
})
}
/**
* Detects whether a given url is routable by the Next.js router (browser only).
*/
export function isLocalURL(url: string): boolean {
// prevent a hydration mismatch on href for url with anchor refs
if (!isAbsoluteUrl(url)) return true
try {
// absolute urls can be local if they are on the same origin
const locationOrigin = getLocationOrigin()
const resolved = new URL(url, locationOrigin)
return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)
} catch (_) {
return false
}
}
type Url = UrlObject | string
export function interpolateAs(
route: string,
asPathname: string,
query: ParsedUrlQuery
) {
let interpolatedRoute = ''
const dynamicRegex = getRouteRegex(route)
const dynamicGroups = dynamicRegex.groups
const dynamicMatches =
// Try to match the dynamic route against the asPath
(asPathname !== route ? getRouteMatcher(dynamicRegex)(asPathname) : '') ||
// Fall back to reading the values from the href
// TODO: should this take priority; also need to change in the router.
query
interpolatedRoute = route
const params = Object.keys(dynamicGroups)
if (
!params.every((param) => {
let value = dynamicMatches[param] || ''
const { repeat, optional } = dynamicGroups[param]
// support single-level catch-all
// TODO: more robust handling for user-error (passing `/`)
let replaced = `[${repeat ? '...' : ''}${param}]`
if (optional) {
replaced = `${!value ? '/' : ''}[${replaced}]`
}
if (repeat && !Array.isArray(value)) value = [value]
return (
(optional || param in dynamicMatches) &&
// Interpolate group into data URL if present
(interpolatedRoute =
interpolatedRoute!.replace(
replaced,
repeat
? (value as string[])
.map(
// these values should be fully encoded instead of just
// path delimiter escaped since they are being inserted
// into the URL and we expect URL encoded segments
// when parsing dynamic route params
(segment) => encodeURIComponent(segment)
)
.join('/')
: encodeURIComponent(value as string)
) || '/')
)
})
) {
interpolatedRoute = '' // did not satisfy all requirements
// n.b. We ignore this error because we handle warning for this case in
// development in the `<Link>` component directly.
}
return {
params,
result: interpolatedRoute,
}
}
function omit<T extends { [key: string]: any }, K extends keyof T>(
object: T,
keys: K[]
): Omit<T, K> {
const omitted: { [key: string]: any } = {}
Object.keys(object).forEach((key) => {
if (!keys.includes(key as K)) {
omitted[key as string] = object[key]
}
})
return omitted as Omit<T, K>
}
/**
* Resolves a given hyperlink with a certain router state (basePath not included).
* Preserves absolute urls.
*/
export function resolveHref(
router: NextRouter,
href: Url,
resolveAs?: boolean
): string {
// we use a dummy base url for relative urls
let base: URL
let urlAsString = typeof href === 'string' ? href : formatWithValidation(href)
// repeated slashes and backslashes in the URL are considered
// invalid and will never match a Next.js page/file
const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//)
const urlAsStringNoProto = urlProtoMatch
? urlAsString.slice(urlProtoMatch[0].length)
: urlAsString
const urlParts = urlAsStringNoProto.split('?')
if ((urlParts[0] || '').match(/(\/\/|\\)/)) {
console.error(
`Invalid href passed to next/router: ${urlAsString}, repeated forward-slashes (//) or backslashes \\ are not valid in the href`
)
const normalizedUrl = normalizeRepeatedSlashes(urlAsStringNoProto)
urlAsString = (urlProtoMatch ? urlProtoMatch[0] : '') + normalizedUrl
}
// Return because it cannot be routed by the Next.js router
if (!isLocalURL(urlAsString)) {
return (resolveAs ? [urlAsString] : urlAsString) as string
}
try {
base = new URL(
urlAsString.startsWith('#') ? router.asPath : router.pathname,
'http://n'
)
} catch (_) {
// fallback to / for invalid asPath values e.g. //
base = new URL('/', 'http://n')
}
try {
const finalUrl = new URL(urlAsString, base)
finalUrl.pathname = normalizePathTrailingSlash(finalUrl.pathname)
let interpolatedAs = ''
if (
isDynamicRoute(finalUrl.pathname) &&
finalUrl.searchParams &&
resolveAs
) {
const query = searchParamsToUrlQuery(finalUrl.searchParams)
const { result, params } = interpolateAs(
finalUrl.pathname,
finalUrl.pathname,
query
)
if (result) {
interpolatedAs = formatWithValidation({
pathname: result,
hash: finalUrl.hash,
query: omit(query, params),
})
}
}
// if the origin didn't change, it means we received a relative href
const resolvedHref =
finalUrl.origin === base.origin
? finalUrl.href.slice(finalUrl.origin.length)
: finalUrl.href
return (
resolveAs ? [resolvedHref, interpolatedAs || resolvedHref] : resolvedHref
) as string
} catch (_) {
return (resolveAs ? [urlAsString] : urlAsString) as string
}
}
function stripOrigin(url: string) {
const origin = getLocationOrigin()
return url.startsWith(origin) ? url.substring(origin.length) : url
}
function prepareUrlAs(router: NextRouter, url: Url, as?: Url) {
// If url and as provided as an object representation,
// we'll format them into the string version here.
let [resolvedHref, resolvedAs] = resolveHref(router, url, true)
const origin = getLocationOrigin()
const hrefHadOrigin = resolvedHref.startsWith(origin)
const asHadOrigin = resolvedAs && resolvedAs.startsWith(origin)
resolvedHref = stripOrigin(resolvedHref)
resolvedAs = resolvedAs ? stripOrigin(resolvedAs) : resolvedAs
const preparedUrl = hrefHadOrigin ? resolvedHref : addBasePath(resolvedHref)
const preparedAs = as
? stripOrigin(resolveHref(router, as))
: resolvedAs || resolvedHref
return {
url: preparedUrl,
as: asHadOrigin ? preparedAs : addBasePath(preparedAs),
}
}
function resolveDynamicRoute(pathname: string, pages: string[]) {
const cleanPathname = removeTrailingSlash(denormalizePagePath(pathname!))
if (cleanPathname === '/404' || cleanPathname === '/_error') {
return pathname
}
// handle resolving href for dynamic routes
if (!pages.includes(cleanPathname!)) {
// eslint-disable-next-line array-callback-return
pages.some((page) => {
if (isDynamicRoute(page) && getRouteRegex(page).re.test(cleanPathname!)) {
pathname = page
return true
}
})
}
return removeTrailingSlash(pathname)
}
export type BaseRouter = {
route: string
pathname: string
query: ParsedUrlQuery
asPath: string
basePath: string
locale?: string | undefined
locales?: string[] | undefined
defaultLocale?: string | undefined
domainLocales?: DomainLocale[] | undefined
isLocaleDomain: boolean
}
export type NextRouter = BaseRouter &
Pick<
Router,
| 'push'
| 'replace'
| 'reload'
| 'back'
| 'prefetch'
| 'beforePopState'
| 'events'
| 'isFallback'
| 'isReady'
| 'isPreview'
>
export type PrefetchOptions = {
priority?: boolean
locale?: string | false
unstable_skipClientCache?: boolean
}
export type PrivateRouteInfo =
| (Omit<CompletePrivateRouteInfo, 'styleSheets'> & { initial: true })
| CompletePrivateRouteInfo
export type CompletePrivateRouteInfo = {
Component: ComponentType
styleSheets: StyleSheetTuple[]
__N_SSG?: boolean
__N_SSP?: boolean
__N_RSC?: boolean
props?: Record<string, any>
err?: Error
error?: any
route?: string
resolvedAs?: string
query?: ParsedUrlQuery
}
export type AppProps = Pick<CompletePrivateRouteInfo, 'Component' | 'err'> & {
router: Router
} & Record<string, any>
export type AppComponent = ComponentType<AppProps>
type Subscription = (
data: PrivateRouteInfo,
App: AppComponent,
resetScroll: { x: number; y: number } | null
) => Promise<void>
type BeforePopStateCallback = (state: NextHistoryState) => boolean
type ComponentLoadCancel = (() => void) | null
type HistoryMethod = 'replaceState' | 'pushState'
const manualScrollRestoration =
process.env.__NEXT_SCROLL_RESTORATION &&
typeof window !== 'undefined' &&
'scrollRestoration' in window.history &&
!!(function () {
try {
let v = '__next'
// eslint-disable-next-line no-sequences
return sessionStorage.setItem(v, v), sessionStorage.removeItem(v), true
} catch (n) {}
})()
const SSG_DATA_NOT_FOUND = Symbol('SSG_DATA_NOT_FOUND')
function fetchRetry(
url: string,
attempts: number,
options: Pick<RequestInit, 'method' | 'headers'>
): Promise<Response> {
return fetch(url, {
// Cookies are required to be present for Next.js' SSG "Preview Mode".
// Cookies may also be required for `getServerSideProps`.
//
// > `fetch` won’t send cookies, unless you set the credentials init
// > option.
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
//
// > For maximum browser compatibility when it comes to sending &
// > receiving cookies, always supply the `credentials: 'same-origin'`
// > option instead of relying on the default.
// https://github.com/github/fetch#caveats
credentials: 'same-origin',
method: options.method || 'GET',
headers: Object.assign({}, options.headers, {
'x-nextjs-data': '1',
}),
}).then((response) => {
return !response.ok && attempts > 1 && response.status >= 500
? fetchRetry(url, attempts - 1, options)
: response
})
}
const backgroundCache: Record<string, Promise<any>> = {}
interface FetchDataOutput {
dataHref: string
json: Record<string, any>
response: Response
text: string
}
interface FetchNextDataParams {
dataHref: string
isServerRender: boolean
parseJSON: boolean | undefined
hasMiddleware?: boolean
inflightCache: NextDataCache
persistCache: boolean
isPrefetch: boolean
isBackground?: boolean
unstable_skipClientCache?: boolean
}
function fetchNextData({
dataHref,
inflightCache,
isPrefetch,
hasMiddleware,
isServerRender,
parseJSON,
persistCache,
isBackground,
unstable_skipClientCache,
}: FetchNextDataParams): Promise<FetchDataOutput> {
const { href: cacheKey } = new URL(dataHref, window.location.href)
const getData = (params?: { method?: 'HEAD' | 'GET' }) =>
fetchRetry(dataHref, isServerRender ? 3 : 1, {
headers: isPrefetch ? { purpose: 'prefetch' } : {},
method: params?.method ?? 'GET',
})
.then((response) => {
if (response.ok && params?.method === 'HEAD') {
return { dataHref, response, text: '', json: {} }
}
return response.text().then((text) => {
if (!response.ok) {
/**
* When the data response is a redirect because of a middleware
* we do not consider it an error. The headers must bring the
* mapped location.
* TODO: Change the status code in the handler.
*/
if (
hasMiddleware &&
[301, 302, 307, 308].includes(response.status)
) {
return { dataHref, response, text, json: {} }
}
if (response.status === 404) {
if (tryToParseAsJSON(text)?.notFound) {
return {
dataHref,
json: { notFound: SSG_DATA_NOT_FOUND },
response,
text,
}
}
/**
* If there is a 404 that is not for SSG we used to fail but if
* there is a middleware we must respond with an empty object.
* For now we will return the data when there is a middleware.
* TODO: Update the server to success on these requests.
*/
if (hasMiddleware) {
return { dataHref, response, text, json: {} }
}
}
const error = new Error(`Failed to load static props`)
/**
* We should only trigger a server-side transition if this was
* caused on a client-side transition. Otherwise, we'd get into
* an infinite loop.
*/
if (!isServerRender) {
markAssetError(error)
}
throw error
}
return {
dataHref,
json: parseJSON ? tryToParseAsJSON(text) : {},
response,
text,
}
})
})
.then((data) => {
if (
!persistCache ||
process.env.NODE_ENV !== 'production' ||
data.response.headers.get('x-middleware-cache') === 'no-cache'
) {
delete inflightCache[cacheKey]
}
return data
})
.catch((err) => {
delete inflightCache[cacheKey]
throw err
})
// when skipping client cache we wait to update
// inflight cache until successful data response
// this allows racing click event with fetching newer data
// without blocking navigation when stale data is available
if (unstable_skipClientCache && persistCache) {
return getData({}).then((data) => {
inflightCache[cacheKey] = Promise.resolve(data)
return data
})
}
if (inflightCache[cacheKey] !== undefined) {
return inflightCache[cacheKey]
}
return (inflightCache[cacheKey] = getData(
isBackground ? { method: 'HEAD' } : {}
))
}
function tryToParseAsJSON(text: string) {
try {
return JSON.parse(text)
} catch (error) {
return {}
}
}
interface NextDataCache {
[asPath: string]: Promise<FetchDataOutput>
}
export function createKey() {
return Math.random().toString(36).slice(2, 10)
}
function handleHardNavigation({
url,
router,
}: {
url: string
router: Router
}) {
// ensure we don't trigger a hard navigation to the same
// URL as this can end up with an infinite refresh
if (url === addBasePath(addLocale(router.asPath, router.locale))) {
throw new Error(
`Invariant: attempted to hard navigate to the same URL ${url} ${location.href}`
)
}
window.location.href = url
}
const getCancelledHandler = ({
route,
router,
}: {
route: string
router: Router
}) => {
let cancelled = false
const cancel = (router.clc = () => {
cancelled = true
})
const handleCancelled = () => {
if (cancelled) {
const error: any = new Error(
`Abort fetching component for route: "${route}"`
)
error.cancelled = true
throw error
}
if (cancel === router.clc) {
router.clc = null
}
}
return handleCancelled
}
export default class Router implements BaseRouter {
basePath: string
/**
* Map of all components loaded in `Router`
*/
components: { [pathname: string]: PrivateRouteInfo }
// Server Data Cache
sdc: NextDataCache = {}
sub: Subscription
clc: ComponentLoadCancel
pageLoader: PageLoader
_bps: BeforePopStateCallback | undefined
events: MittEmitter<RouterEvent>
_wrapApp: (App: AppComponent) => any
isSsr: boolean
_inFlightRoute?: string | undefined
_shallow?: boolean | undefined
locales?: string[] | undefined
defaultLocale?: string | undefined
domainLocales?: DomainLocale[] | undefined
isReady: boolean
isLocaleDomain: boolean
isFirstPopStateEvent = true
_initialMatchesMiddlewarePromise: Promise<boolean>
private state: Readonly<{
route: string
pathname: string
query: ParsedUrlQuery
asPath: string
locale: string | undefined
isFallback: boolean
isPreview: boolean
}>
private _key: string = createKey()
static events: MittEmitter<RouterEvent> = mitt()
constructor(
pathname: string,
query: ParsedUrlQuery,
as: string,
{
initialProps,
pageLoader,
App,
wrapApp,
Component,
err,
subscription,
isFallback,
locale,
locales,
defaultLocale,
domainLocales,
isPreview,
isRsc,
}: {
subscription: Subscription
initialProps: any
pageLoader: any
Component: ComponentType
App: AppComponent
wrapApp: (WrapAppComponent: AppComponent) => any
err?: Error
isFallback: boolean
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocale[]
isPreview?: boolean
isRsc?: boolean
}
) {
// represents the current component key
const route = removeTrailingSlash(pathname)
// set up the component cache (by route keys)
this.components = {}
// We should not keep the cache, if there's an error
// Otherwise, this cause issues when when going back and
// come again to the errored page.
if (pathname !== '/_error') {
this.components[route] = {
Component,
initial: true,
props: initialProps,
err,
__N_SSG: initialProps && initialProps.__N_SSG,
__N_SSP: initialProps && initialProps.__N_SSP,
__N_RSC: !!isRsc,
}
}
this.components['/_app'] = {
Component: App as ComponentType,
styleSheets: [
/* /_app does not need its stylesheets managed */
],
}
// Backwards compat for Router.router.events
// TODO: Should be remove the following major version as it was never documented
this.events = Router.events
this.pageLoader = pageLoader
// if auto prerendered and dynamic route wait to update asPath
// until after mount to prevent hydration mismatch
const autoExportDynamic =
isDynamicRoute(pathname) && self.__NEXT_DATA__.autoExport
this.basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''
this.sub = subscription
this.clc = null
this._wrapApp = wrapApp
// make sure to ignore extra popState in safari on navigating
// back from external site
this.isSsr = true
this.isLocaleDomain = false
this.isReady = !!(
self.__NEXT_DATA__.gssp ||
self.__NEXT_DATA__.gip ||
(self.__NEXT_DATA__.appGip && !self.__NEXT_DATA__.gsp) ||
(!autoExportDynamic &&
!self.location.search &&
!process.env.__NEXT_HAS_REWRITES)
)
if (process.env.__NEXT_I18N_SUPPORT) {
this.locales = locales
this.defaultLocale = defaultLocale
this.domainLocales = domainLocales
this.isLocaleDomain = !!detectDomainLocale(
domainLocales,
self.location.hostname
)
}
this.state = {
route,
pathname,
query,
asPath: autoExportDynamic ? pathname : as,
isPreview: !!isPreview,
locale: process.env.__NEXT_I18N_SUPPORT ? locale : undefined,
isFallback,
}
this._initialMatchesMiddlewarePromise = Promise.resolve(false)
if (typeof window !== 'undefined') {
// make sure "as" doesn't start with double slashes or else it can
// throw an error as it's considered invalid
if (!as.startsWith('//')) {
// in order for `e.state` to work on the `onpopstate` event
// we have to register the initial route upon initialization
const options: TransitionOptions = { locale }
const asPath = getURL()
this._initialMatchesMiddlewarePromise = matchesMiddleware({
router: this,
locale,
asPath,
}).then((matches) => {
// if middleware matches we leave resolving to the change function
// as the server needs to resolve for correct priority
;(options as any)._shouldResolveHref = as !== pathname
this.changeState(
'replaceState',
matches
? asPath
: formatWithValidation({
pathname: addBasePath(pathname),
query,
}),
asPath,
options
)
return matches
})
}
window.addEventListener('popstate', this.onPopState)
// enable custom scroll restoration handling when available
// otherwise fallback to browser's default handling
if (process.env.__NEXT_SCROLL_RESTORATION) {
if (manualScrollRestoration) {
window.history.scrollRestoration = 'manual'
}
}
}
}
onPopState = (e: PopStateEvent): void => {
const { isFirstPopStateEvent } = this
this.isFirstPopStateEvent = false
const state = e.state as HistoryState
if (!state) {
// We get state as undefined for two reasons.
// 1. With older safari (< 8) and older chrome (< 34)
// 2. When the URL changed with #
//
// In the both cases, we don't need to proceed and change the route.
// (as it's already changed)
// But we can simply replace the state with the new changes.
// Actually, for (1) we don't need to nothing. But it's hard to detect that event.
// So, doing the following for (1) does no harm.
const { pathname, query } = this
this.changeState(
'replaceState',
formatWithValidation({ pathname: addBasePath(pathname), query }),
getURL()
)
return
}
if (!state.__N) {
return
}
// Safari fires popstateevent when reopening the browser.
if (
isFirstPopStateEvent &&
this.locale === state.options.locale &&
state.as === this.asPath
) {
return
}
let forcedScroll: { x: number; y: number } | undefined
const { url, as, options, key } = state
if (process.env.__NEXT_SCROLL_RESTORATION) {
if (manualScrollRestoration) {
if (this._key !== key) {
// Snapshot current scroll position:
try {
sessionStorage.setItem(
'__next_scroll_' + this._key,
JSON.stringify({ x: self.pageXOffset, y: self.pageYOffset })
)
} catch {}
// Restore old scroll position:
try {
const v = sessionStorage.getItem('__next_scroll_' + key)
forcedScroll = JSON.parse(v!)
} catch {
forcedScroll = { x: 0, y: 0 }
}
}
}
}
this._key = key
const { pathname } = parseRelativeUrl(url)
// Make sure we don't re-render on initial load,
// can be caused by navigating back from an external site
if (
this.isSsr &&
as === addBasePath(this.asPath) &&
pathname === addBasePath(this.pathname)
) {
return
}
// If the downstream application returns falsy, return.
// They will then be responsible for handling the event.
if (this._bps && !this._bps(state)) {
return
}
this.change(
'replaceState',
url,
as,
Object.assign<{}, TransitionOptions, TransitionOptions>({}, options, {
shallow: options.shallow && this._shallow,
locale: options.locale || this.defaultLocale,
}),
forcedScroll
)
}
reload(): void {
window.location.reload()
}
/**
* Go back in history
*/
back() {
window.history.back()
}
/**
* Performs a `pushState` with arguments
* @param url of the route
* @param as masks `url` for the browser
* @param options object you can define `shallow` and other options
*/
push(url: Url, as?: Url, options: TransitionOptions = {}) {
if (process.env.__NEXT_SCROLL_RESTORATION) {
// TODO: remove in the future when we update history before route change
// is complete, as the popstate event should handle this capture.
if (manualScrollRestoration) {
try {
// Snapshot scroll position right before navigating to a new page:
sessionStorage.setItem(
'__next_scroll_' + this._key,
JSON.stringify({ x: self.pageXOffset, y: self.pageYOffset })
)
} catch {}
}
}
;({ url, as } = prepareUrlAs(this, url, as))
return this.change('pushState', url, as, options)
}
/**
* Performs a `replaceState` with arguments
* @param url of the route
* @param as masks `url` for the browser
* @param options object you can define `shallow` and other options
*/
replace(url: Url, as?: Url, options: TransitionOptions = {}) {
;({ url, as } = prepareUrlAs(this, url, as))
return this.change('replaceState', url, as, options)
}
private async change(
method: HistoryMethod,
url: string,
as: string,
options: TransitionOptions,
forcedScroll?: { x: number; y: number }
): Promise<boolean> {
if (!isLocalURL(url)) {
handleHardNavigation({ url, router: this })
return false
}
// WARNING: `_h` is an internal option for handing Next.js client-side
// hydration. Your app should _never_ use this property. It may change at
// any time without notice.
const isQueryUpdating = (options as any)._h
const shouldResolveHref =
isQueryUpdating ||
(options as any)._shouldResolveHref ||
parsePath(url).pathname === parsePath(as).pathname
const nextState = {
...this.state,
}
// for static pages with query params in the URL we delay
// marking the router ready until after the query is updated
// or a navigation has occurred
this.isReady = true
const isSsr = this.isSsr
if (!isQueryUpdating) {
this.isSsr = false
}
// if a route transition is already in progress before
// the query updating is triggered ignore query updating
if (isQueryUpdating && this.clc) {
return false
}
const prevLocale = nextState.locale
if (process.env.__NEXT_I18N_SUPPORT) {
nextState.locale =