Skip to content

Commit 965d330

Browse files
Add an example on why singletones are bad (#1298)
Co-authored-by: Natalia Tepluhina <tarya.se@gmail.com>
1 parent 210b792 commit 965d330

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/guide/ssr/structure.md

+26-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,32 @@
44

55
When writing client-only code, we can assume that our code will be evaluated in a fresh context every time. However, a Node.js server is a long-running process. When our code is first imported by the process, it will be evaluated once and then stay in memory. This means that if you create a singleton object, it will be shared between every incoming request, with the risk of cross-request state pollution.
66

7-
Therefore, we need to **create a new root Vue instance for each request.** In order to do that, we need to write a factory function that can be repeatedly executed to create fresh app instances for each request, so our server code now becomes:
7+
```js
8+
// bad
9+
import app from './app.js'
10+
11+
server.get('*', async (req, res) => {
12+
// the app is now shared amongst all users
13+
const result = await renderToString(app)
14+
// ...
15+
})
16+
```
17+
18+
```js
19+
// good
20+
function createApp() {
21+
return createSSRApp(/* ... */)
22+
}
23+
24+
server.get('*', async (req, res) => {
25+
// each user gets its own app
26+
const app = createApp()
27+
const result = await renderToString(app)
28+
// ...
29+
})
30+
```
31+
32+
Therefore, we need to **create a new root Vue instance for each request.** In order to do that, we need to write a factory function that can be repeatedly executed to create fresh app instances for each request:
833

934
```js
1035
// server.js

0 commit comments

Comments
 (0)