-
-
Notifications
You must be signed in to change notification settings - Fork 348
/
index.js
70 lines (61 loc) · 2.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// This file isn't processed by Vite, see https://github.com/vikejs/vike/issues/562
// Consequently:
// - When changing this file, you needed to manually restart your server for your changes to take effect.
// - To use your environment variables defined in your .env files, you need to install dotenv, see https://vike.dev/env
// - To use your path aliases defined in your vite.config.js, you need to tell Node.js about them, see https://vike.dev/path-aliases
import express from 'express'
import { renderPage } from 'vike/server'
import { root } from './root.js'
import fetch from 'node-fetch'
import apollo from '@apollo/client'
const { ApolloClient, createHttpLink, InMemoryCache } = apollo
const isProduction = process.env.NODE_ENV === 'production'
startServer()
async function startServer() {
const app = express()
if (isProduction) {
app.use(express.static(`${root}/dist/client`))
} else {
const vite = await import('vite')
const viteDevMiddleware = (
await vite.createServer({
root,
server: { middlewareMode: true }
})
).middlewares
app.use(viteDevMiddleware)
}
app.get('*', async (req, res, next) => {
// It's important to create an entirely new instance of Apollo Client for each request.
// Otherwise, our response to a request might include sensitive cached query results
// from a previous request. Source: https://www.apollographql.com/docs/react/performance/server-side-rendering/#example
const apolloClient = makeApolloClient()
const pageContextInit = {
urlOriginal: req.originalUrl,
apolloClient
}
const pageContext = await renderPage(pageContextInit)
const { httpResponse } = pageContext
if (!httpResponse) {
return next()
} else {
const { body, statusCode, headers } = httpResponse
headers.forEach(([name, value]) => res.setHeader(name, value))
res.status(statusCode).send(body)
}
})
const port = 3000
app.listen(port)
console.log(`Server running at http://localhost:${port}`)
}
function makeApolloClient() {
const apolloClient = new ApolloClient({
ssrMode: true,
link: createHttpLink({
uri: 'https://countries.trevorblades.com',
fetch
}),
cache: new InMemoryCache()
})
return apolloClient
}