Skip to content

SSR Guide: Add an example on why singletones are bad #1298

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 27, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/guide/ssr/structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,32 @@

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.

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:
```js
// bad
import app from './app.js'

server.get('*', async (req, res) => {
// the app is now shared amongst all users
const result = await renderToString(app)
// ...
})
```

```js
// good
function createApp() {
return createSSRApp(/* ... */)
}

server.get('*', async (req, res) => {
// each user gets its own app
const app = createApp()
const result = await renderToString(app)
// ...
})
```

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:

```js
// server.js
Expand Down