@@ -6,7 +6,7 @@ let router = null
6
6
const SingletonRouter = { }
7
7
8
8
// Create public properties and methods of the router in the SingletonRouter
9
- const propertyFields = [ 'route ' , 'components ' , 'pathname ' , 'query' ]
9
+ const propertyFields = [ 'components ' , 'pathname ' , 'route ' , 'query' ]
10
10
const methodFields = [ 'push' , 'replace' , 'reload' , 'back' ]
11
11
12
12
propertyFields . forEach ( ( field ) => {
@@ -16,36 +16,41 @@ propertyFields.forEach((field) => {
16
16
// proper way to access it
17
17
Object . defineProperty ( SingletonRouter , field , {
18
18
get ( ) {
19
+ throwIfNoRouter ( )
19
20
return router [ field ]
20
21
}
21
22
} )
22
23
} )
23
24
24
25
methodFields . forEach ( ( field ) => {
25
26
SingletonRouter [ field ] = ( ...args ) => {
27
+ throwIfNoRouter ( )
26
28
return router [ field ] ( ...args )
27
29
}
28
30
} )
29
31
30
- // This is an internal method and it should not be called directly.
31
- //
32
- // ## Client Side Usage
33
- // We create the router in the client side only for a single time when we are
34
- // booting the app. It happens before rendering any components.
35
- // At the time of the component rendering, there'll be a router instance
36
- //
37
- // ## Server Side Usage
38
- // We create router for every SSR page render.
39
- // Since rendering happens in the same eventloop this works properly.
32
+ function throwIfNoRouter ( ) {
33
+ if ( ! router ) {
34
+ const message = 'No router instance found.\n' +
35
+ 'You should only use "next/router" inside the client side of your app.\n'
36
+ throw new Error ( message )
37
+ }
38
+ }
39
+
40
+ // Export the SingletonRouter and this is the public API.
41
+ export default SingletonRouter
42
+
43
+ // INTERNAL APIS
44
+ // -------------
45
+ // (do not use following exports inside the app)
46
+
47
+ // Create a router and assign it as the singleton instance.
48
+ // This is used in client side when we are initilizing the app.
49
+ // This should **not** use inside the server.
40
50
export const createRouter = function ( ...args ) {
41
51
router = new _Router ( ...args )
42
52
return router
43
53
}
44
54
45
- // Export the actual Router class, which is also use internally
46
- // You'll ever need to access this directly
55
+ // Export the actual Router class, which is usually used inside the server
47
56
export const Router = _Router
48
-
49
- // Export the SingletonRouter and this is the public API.
50
- // This is an client side API and doesn't available on the server
51
- export default SingletonRouter
0 commit comments