Vue3 Api Createssrapp
## Vue3 `createSSRApp()` API Tutorial
`createSSRApp()` is a specialized global API in Vue 3 designed specifically for Server-Side Rendering (SSR).
By rendering HTML content on the server side, `createSSRApp()` significantly improves initial page load performance and Search Engine Optimization (SEO). Compared to the standard `createApp()`, `createSSRApp()` is tailored for applications that require hydration of pre-rendered server HTML on the client side.
---
## 1. What is Server-Side Rendering (SSR)?
**Server-Side Rendering (SSR)** is the process of generating static HTML markup on the server in response to a request, and then sending that fully formed HTML directly to the client's browser.
This differs from traditional **Client-Side Rendering (CSR)**:
* **In CSR:** The browser downloads a minimal, empty HTML file along with a large JavaScript bundle. The browser then executes the JavaScript to build the DOM and render the page content dynamically.
* **In SSR:** The server does the heavy lifting of rendering the initial page. The browser receives a fully populated HTML document, allowing users to see the content immediately. Once the JavaScript bundle loads, Vue "hydrates" the static HTML to make it interactive.
---
## 2. The Role of `createSSRApp()`
In Vue 3, `createApp()` is the standard function used to bootstrap client-only applications. `createSSRApp()`, on the other hand, is a specialized variant.
Its primary responsibilities are:
1. **On the Server:** It bootstraps the application instance so that renderer APIs (like `@vue/server-renderer`) can stringify the component tree into static HTML.
2. **On the Client:** Instead of creating new DOM nodes from scratch and overwriting the existing container, `createSSRApp()` mounts the application in **Hydration Mode**. It scans the server-rendered HTML, matches it with the virtual DOM, and attaches event listeners to make the static page interactive without causing visual flickers.
---
## 3. How to Use `createSSRApp()`
Using `createSSRApp()` is syntactically very similar to `createApp()`, but the architectural setup requires handling both server and client environments.
### 3.1 Basic Usage
```javascript
// Import createSSRApp from Vue
import { createSSRApp } from 'vue';
// Import the root component
import App from './App.vue';
// Create the SSR-compatible application instance
const app = createSSRApp(App);
// Mount the application (performs hydration on the client)
app.mount('#app');
```
In this setup, when the client-side bundle runs, `createSSRApp()` will attempt to hydrate the existing HTML inside the `#app` container instead of replacing it.
### 3.2 Server-Side vs. Client-Side Behavior
The behavior of `createSSRApp()` adapts depending on where the code is executed:
* **Server-Side:** It initializes the application state and component tree. A server framework (like Express or Koa) uses Vue's server renderer to convert this instance into an HTML string, which is sent to the client.
* **Client-Side:** It boots up the application, matches the DOM structure generated by the server, and activates reactivity (hydration).
### 3.3 SSR Configuration and Best Practices
When building SSR applications, you must write "universal" (isomorphic) code that runs on both the server and the client. Keep the following in mind:
* **Avoid Client-Only APIs on the Server:** Global objects like `window`, `document`, or `localStorage` do not exist in the Node.js server environment. Accessing them directly during the creation or setup phase will throw errors.
* **Use the `onServerPrefetch` Lifecycle Hook:** To fetch asynchronous data on the server before rendering the HTML, use the `onServerPrefetch` hook.
#### Example: Prefetching Data on the Server
```javascript
import { ref, onServerPrefetch, onMounted } from 'vue';
import { fetchData } from './api';
export default {
setup() {
const data = ref(null);
// Helper function to load data
const loadData = async () => {
data.value = await fetchData();
};
// Executed on the server during rendering
onServerPrefetch(async () => {
await loadData();
});
// Executed on the client if data wasn't fetched on the server
onMounted(async () => {
if (!data.value) {
await loadData();
}
});
return { data };
}
};
```
---
## 4. `createApp()` vs. `createSSRApp()`
| Feature | `createApp()` | `createSSRApp()` |
| :--- | :--- | :--- |
| **Rendering Environment** | Client-Side Rendering (CSR) | Server-Side Rendering (SSR) & Hydration |
| **Initial Load Speed** | Slower (depends on client JS download and execution) | Faster (browser displays pre-rendered HTML immediately) |
| **SEO Performance** | Poor (search engine crawlers may struggle with dynamic JS) | Excellent (crawlers receive fully rendered HTML) |
| **Mounting Behavior** | Overwrites the target DOM container completely | Hydrates and activates existing server-rendered HTML |
| **Primary Use Case** | Single Page Applications (SPAs), Admin Dashboards | Content-heavy sites, E-commerce, Blogs, Public Landing Pages |
YouTip