From b9f6e20510a209fe4f3cb00146f489047373cebd Mon Sep 17 00:00:00 2001 From: Stanislav Lashmanov Date: Tue, 26 Oct 2021 16:21:13 +0300 Subject: [PATCH] Add an example on why singletones are bad --- src/guide/ssr/structure.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/guide/ssr/structure.md b/src/guide/ssr/structure.md index 1fe86d676a..4686c06784 100644 --- a/src/guide/ssr/structure.md +++ b/src/guide/ssr/structure.md @@ -4,6 +4,31 @@ 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. +```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