What Causes This Error?
This error occurs when you use useSSRContext() with Vue’s global/CDN build instead of the bundler build. The SSR context is only available when using a bundler like Vite or webpack.
The Problem
<!-- ❌ Using CDN build with SSR features -->
<script src="https://unpkg.com/vue@3"></script>
<script>
const { useSSRContext } = Vue
// In a component
const ssrContext = useSSRContext() // Error!
</script>
The Fix
Use a Bundler
// ✅ With Vite/webpack, SSR context works
import { useSSRContext } from 'vue'
export default {
setup() {
const ctx = useSSRContext()
// Use ctx for SSR-specific data
}
}
Check Environment
import { useSSRContext } from 'vue'
export default {
setup() {
// ✅ Only use in SSR environment
if (import.meta.env.SSR) {
const ctx = useSSRContext()
ctx.someData = 'value'
}
}
}
Common Scenarios
Nuxt Usage
<script setup>
// ✅ Nuxt provides useSSRContext automatically
const ssrContext = useSSRContext()
if (ssrContext) {
// Running on server
ssrContext.nuxt.payload.data = 'server data'
}
</script>
Conditional SSR Logic
// utils/ssr.js
export function getSSRContext() {
if (typeof window === 'undefined') {
try {
const { useSSRContext } = require('vue')
return useSSRContext()
} catch {
return null
}
}
return null
}
Vite SSR Setup
// entry-server.js
import { createSSRApp } from 'vue'
import { renderToString } from 'vue/server-renderer'
import App from './App.vue'
export async function render(url, manifest) {
const app = createSSRApp(App)
const ctx = {}
const html = await renderToString(app, ctx)
return { html }
}
When You Don’t Need SSR
If you’re building a client-only SPA, you don’t need useSSRContext():
// ✅ For client-only apps, use regular Vue
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
Quick Checklist
- Use bundler (Vite/webpack) for SSR features
- Check
import.meta.env.SSRbefore using SSR context - Don’t use CDN build for SSR applications
- Use
createSSRAppfor SSR applications - Client-only apps don’t need
useSSRContext