question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Example of how to fetch API data for SSR

See original GitHub issue

I am looking for a example of how I can achieve SSR with loadable-components that would also fetch dynamic data needed for he component of the route and have that rendered server side…

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:14 (8 by maintainers)

github_iconTop GitHub Comments

4reactions
gregbergecommented, Nov 30, 2018

This is my SSR middleware:

import path from 'path'
import React from 'react'
import { ServerStyleSheet } from 'styled-components'
import { renderToString, renderToNodeStream } from 'react-dom/server'
import { StaticRouter } from 'react-router'
import { HelmetProvider } from 'react-helmet-async'
import { ApolloProvider, getDataFromTree } from 'react-apollo'
import { ChunkExtractor } from '@loadable/server'
import config, { getClientConfig } from 'server/config'
import Head from 'server/components/Head'
import Body from 'server/components/Body'
import { asyncMiddleware } from 'server/utils/express'
import { createApolloClient } from 'server/graphql/apolloClient'

const nodeStats = path.resolve(
  config.get('server.publicPath'),
  'dist/node/loadable-stats.json',
)

const webStats = path.resolve(
  config.get('server.publicPath'),
  'dist/web/loadable-stats.json',
)

const ssr = asyncMiddleware(async (req, res) => {
  const nodeExtractor = new ChunkExtractor({
    statsFile: nodeStats,
    outputPath: path.join(config.get('server.publicPath'), 'dist/node'),
  })
  const { default: App } = nodeExtractor.requireEntrypoint()

  const webExtractor = new ChunkExtractor({ statsFile: webStats })

  const apolloClient = createApolloClient()
  const routerContext = {}
  const helmetContext = {}

  const app = (
    <ApolloProvider client={apolloClient}>
      <HelmetProvider context={helmetContext}>
        <StaticRouter location={req.url} context={routerContext}>
          <App />
        </StaticRouter>
      </HelmetProvider>
    </ApolloProvider>
  )

  // Styled components
  const sheet = new ServerStyleSheet()
  let jsx = sheet.collectStyles(app)
  jsx = webExtractor.collectChunks(app)

  // Apollo
  await getDataFromTree(jsx)
  const apolloState = apolloClient.extract()

  // Handle React router status
  if (routerContext.status) {
    res.status(routerContext.status)
  }

  // Handle React Router redirection
  if (routerContext.url) {
    const status = routerContext.status === 301 ? 301 : 302
    res.redirect(status, routerContext.url)
    return
  }

  const { helmet } = helmetContext
  const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx))

  const head = renderToString(<Head helmet={helmet} extractor={webExtractor} />)
  res.set('content-type', 'text/html')
  res.write(
    `<!DOCTYPE html><html ${helmet.htmlAttributes}><head>${head}</head><body ${
      helmet.bodyAttributes
    }><div id="main">`,
  )
  stream.pipe(
    res,
    { end: false },
  )
  stream.on('end', () => {
    const body = renderToString(
      <Body
        config={getClientConfig()}
        helmet={helmet}
        extractor={webExtractor}
        apolloState={apolloState}
      />,
    )
    res.end(`</div>${body}</body></html>`)
  })
})

export default ssr
0reactions
zhipenglincommented, Mar 4, 2019

@adardesign this is not the responsibility of loadable-components, you should try to use Apollo for GraphQL or another alternative for REST API.

I’m also confused about this.It would be great if there were examples to tell me what to do.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Interactive Guide to SSR for Fetching APIs in Next.js - RapidAPI
Next.js provides Server Side Rendering (SSR) as a way of data fetching. Let's see how we can fetch data from APIs using SSR....
Read more >
Data Fetching: Overview - Next.js
Next.js allows you to fetch data in multiple ways, with pre-rendering, server-side rendering or static-site generation, and incremental static regeneration.
Read more >
Fetch data from an API on the server-side with ... - Egghead.io
In this lesson, we will learn how to use getServerSideProps to dynamically fetch data and server-side render pages by consuming a "user profile"...
Read more >
Fetching API Data with Web Components and SSR
In the Promise, I used fetch to make the HTTP request to /api/blog . I call res() after the component renders the view...
Read more >
Understanding Next.js Data Fetching (CSR, SSR, SSG, ISR)
CSR - Client-Side Rendering, this is the usual kind of data fetching using useEffect , it will fetch the data from the API...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found