react-router-dom#StaticRouter JavaScript Examples
The following examples show how to use
react-router-dom#StaticRouter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js From citr-v6-project with Apache License 2.0 | 6 votes |
app.use((req, res) => {
res.write(parts[0]);
const staticContext = {};
const reactMarkup = (
<StaticRouter url={req.url} context={staticContext}>
<App />
</StaticRouter>
);
const stream = renderToNodeStream(reactMarkup);
stream.pipe(res, { end: false });
stream.on("end", () => {
res.status(staticContext.statusCode || 200);
res.write(parts[1]);
res.end();
});
});
Example #2
Source File: constructor-edit.spec.js From horondi_admin with MIT License | 6 votes |
describe('constructor-edit tests', () => {
test('Should render constructor-edit', () => {
wrapper = mount(
<StaticRouter
store={mockStore}
location='/constructor-list/60eadfb9e913fc288294bd9'
>
<Switch>
<Route
path='/constructor-list/:id'
exact
component={constructorEdit}
/>
</Switch>
</StaticRouter>
);
expect(wrapper).toBeDefined();
});
});
Example #3
Source File: serverRouter.js From Senior-FrontEnd with MIT License | 6 votes |
router.get("*", async function (req, res, next) {
let data = {}
let getData = null
routes.some(route => {
const match = matchPath(req.path, route);
if (match) {
getData = (route.component || {}).getData
}
return match
});
if (typeof getData === 'function') {
try {
data = await getData()
} catch (error) { }
}
const appString = ReactDOMServer.renderToString(
<StaticRouter
location={req.url}
context={data}
>
<App />
</StaticRouter>)
const html = ReactDOMServer.renderToStaticMarkup(<Document data={data}>
{appString}
</Document>)
res.status(200).send(html);
});
Example #4
Source File: serverRouter.js From Senior-FrontEnd with MIT License | 6 votes |
router.get("*", function (req, res, next) {
const appString = ReactDOMServer.renderToString(
<StaticRouter
location={req.url}
>
<App />
</StaticRouter>)
const html = ReactDOMServer.renderToStaticMarkup(<Document>
{appString}
</Document>)
console.log('html', html)
res.status(200).send(html);
});
Example #5
Source File: ServerRouter.jsx From movies with MIT License | 6 votes |
ServerRouter = ({
initialLanguage,
helmetContext,
routerContext,
store,
url
}) => {
const i18n = configureI18next(initialLanguage);
return (
<HelmetProvider context={helmetContext}>
<StaticRouter
location={url}
context={routerContext}
>
{renderRoutes(routes, {
store,
i18n
})}
</StaticRouter>
</HelmetProvider>
);
}
Example #6
Source File: ssr.js From ReactCookbook-source with MIT License | 6 votes |
app.use('*', async (req, res) => {
let componentData = {};
let indexHTML = fs.readFileSync(path.resolve(__dirname, '../build/index.html'), {
encoding: 'utf8',
});
let appHTML = renderToString(
<StaticRouter location={req.originalUrl} context={componentData}>
<App/>
</StaticRouter>
);
indexHTML = indexHTML.replace('<div id="root"></div>', `<div id="app">${appHTML}</div>`);
indexHTML = indexHTML.replace(
'var initial_state = null;',
`var initial_state = ${JSON.stringify(componentData)};`
);
// set header and status
res.contentType('text/html');
res.status(200);
return res.send(indexHTML);
});
Example #7
Source File: server.js From ReactCookbook-source with MIT License | 6 votes |
server
.disable('x-powered-by')
.use(express.static(process.env.RAZZLE_PUBLIC_DIR))
.get('/*', (req, res) => {
const context = {};
const markup = renderToString(
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
);
if (context.url) {
res.redirect(context.url);
} else {
res.status(200).send(
`<!doctype html>
<html lang="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<title>Welcome to Razzle</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
${cssLinksFromAssets(assets, 'client')}
</head>
<body>
<div id="root">${markup}</div>
${jsScriptTagsFromAssets(assets, 'client', ' defer crossorigin')}
</body>
</html>`
);
}
});
Example #8
Source File: ssr-handler.js From divar-starter-kit with MIT License | 6 votes |
function getPageMarkup({
store, context, preloadedData, location,
}) {
const { Provider: InitialSSRDataProvider } = createNewContext();
return renderToString(
<Provider store={store}>
<InitialSSRDataProvider value={initSSRContextValue(preloadedData)}>
<StaticRouter context={context} location={location}>
<AppRouter />
</StaticRouter>
</InitialSSRDataProvider>
</Provider>,
);
}
Example #9
Source File: Pet.test.js From citr-v6-project with Apache License 2.0 | 6 votes |
test("displays a non-default thumbnail", async () => {
const pet = render(
<StaticRouter>
<Pet images={["1.jpg", "2.jpg", "3.jpg"]} />
</StaticRouter>
);
const petThumbnail = await pet.findByTestId("thumbnail");
expect(petThumbnail.src).toContain("1.jpg");
});
Example #10
Source File: Pet.test.js From citr-v6-project with Apache License 2.0 | 6 votes |
test("displays a default thumbnail", async () => {
const pet = render(
<StaticRouter>
<Pet />
</StaticRouter>
);
const petThumbnail = await pet.findByTestId("thumbnail");
expect(petThumbnail.src).toContain("none.jpg");
});
Example #11
Source File: index.js From citr-v6-project with Apache License 2.0 | 6 votes |
app.use((req, res) => {
const staticContext = {};
const reactMarkup = (
<StaticRouter url={req.url} context={staticContext}>
<App />
</StaticRouter>
);
res.status(staticContext.statusCode || 200);
res.send(`${parts[0]}${renderToString(reactMarkup)}${parts[1]}`);
res.end();
});
Example #12
Source File: App.jsx From intergalactic with MIT License | 6 votes |
Router = !globalThis.__ssr
? BrowserRouter
: ({ children, basename }) => {
if (globalThis.__ssr_route === undefined) {
throw new Error(`On server side globalThis.__ssr_route should be defined`);
}
const location = !globalThis.__ssr_route ? `/` : `/${globalThis.__ssr_route}/`;
return (
<StaticRouter basename={basename} location={location}>
{children}
</StaticRouter>
);
}
Example #13
Source File: express.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
app.get('*', (req, res) => {
const sheets = new ServerStyleSheets()
const context = {}
const markup = ReactDOMServer.renderToString(
sheets.collect(
<StaticRouter location={req.url} context={context}>
<ThemeProvider theme={theme}>
<MainRouter />
</ThemeProvider>
</StaticRouter>
)
)
if (context.url) {
return res.redirect(303, context.url)
}
const css = sheets.toString()
res.status(200).send(Template({
markup: markup,
css: css
}))
})
Example #14
Source File: express.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
app.get('*', (req, res) => {
const sheets = new ServerStyleSheets()
const context = {}
const markup = ReactDOMServer.renderToString(
sheets.collect(
<StaticRouter location={req.url} context={context}>
<ThemeProvider theme={theme}>
<MainRouter />
</ThemeProvider>
</StaticRouter>
)
)
if (context.url) {
return res.redirect(303, context.url)
}
const css = sheets.toString()
res.status(200).send(Template({
markup: markup,
css: css
}))
})
Example #15
Source File: express.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
app.get('*', (req, res) => {
const sheets = new ServerStyleSheets()
const context = {}
loadBranchData(req.url).then(data => {
const markup = ReactDOMServer.renderToString(
sheets.collect(
<StaticRouter location={req.url} context={context}>
<ThemeProvider theme={theme}>
<MainRouter data={data}/>
</ThemeProvider>
</StaticRouter>
)
)
if (context.url) {
return res.redirect(303, context.url)
}
const css = sheets.toString()
res.status(200).send(Template({
markup: markup,
css: css
}))
}).catch(err => {
res.status(500).send({"error": "Could not load React view with data"})
})
})
Example #16
Source File: express.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
app.get('*', (req, res) => {
const sheets = new ServerStyleSheets()
const context = {}
const markup = ReactDOMServer.renderToString(
sheets.collect(
<StaticRouter location={req.url} context={context}>
<ThemeProvider theme={theme}>
<MainRouter />
</ThemeProvider>
</StaticRouter>
)
)
if (context.url) {
return res.redirect(303, context.url)
}
const css = sheets.toString()
res.status(200).send(Template({
markup: markup,
css: css
}))
})
Example #17
Source File: express.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
app.get('*', (req, res) => {
const sheets = new ServerStyleSheets()
const context = {}
const markup = ReactDOMServer.renderToString(
sheets.collect(
<StaticRouter location={req.url} context={context}>
<ThemeProvider theme={theme}>
<MainRouter/>
</ThemeProvider>
</StaticRouter>
)
)
if (context.url) {
return res.redirect(303, context.url)
}
const css = sheets.toString()
res.status(200).send(Template({
markup: markup,
css: css
}))
})
Example #18
Source File: express.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
app.get('*', (req, res) => {
const sheets = new ServerStyleSheets()
const context = {}
const markup = ReactDOMServer.renderToString(
sheets.collect(
<StaticRouter location={req.url} context={context}>
<ThemeProvider theme={theme}>
<MainRouter/>
</ThemeProvider>
</StaticRouter>
)
)
if (context.url) {
return res.redirect(303, context.url)
}
const css = sheets.toString()
res.status(200).send(Template({
markup: markup,
css: css
}))
})
Example #19
Source File: express.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
app.get('*', (req, res) => {
const sheets = new ServerStyleSheets()
const context = {}
const markup = ReactDOMServer.renderToString(
sheets.collect(
<StaticRouter location={req.url} context={context}>
<ThemeProvider theme={theme}>
<MainRouter />
</ThemeProvider>
</StaticRouter>
)
)
if (context.url) {
return res.redirect(303, context.url)
}
const css = sheets.toString()
res.status(200).send(Template({
markup: markup,
css: css
}))
})
Example #20
Source File: express.js From Full-Stack-React-Projects-Second-Edition with MIT License | 6 votes |
app.get('*', (req, res) => {
const sheets = new ServerStyleSheets()
const context = {}
const markup = ReactDOMServer.renderToString(
sheets.collect(
<StaticRouter location={req.url} context={context}>
<ThemeProvider theme={theme}>
<MainRouter />
</ThemeProvider>
</StaticRouter>
)
)
if (context.url) {
return res.redirect(303, context.url)
}
const css = sheets.toString()
res.status(200).send(Template({
markup: markup,
css: css
}))
})
Example #21
Source File: render.js From tunnel-tool with MIT License | 5 votes |
render = (
{
App,
paths: { resources: RESOURCES_BASE_ROUTE, base: BASE_ROUTE },
urls: {
external: { graphql: EXTERNAL_URL_GRAPH, events: EXTERNAL_URL_EVENTS },
internal: { graphql: INTERNAL_URL_GRAPH, events: INTERNAL_URL_EVENTS }
},
watchers,
reducers,
req,
res
},
cxt
) => {
let routerContext = {};
const { store } = configureStore({ reducers, initState: {} });
const { graph } = configureGraph({
url: INTERNAL_URL_GRAPH,
req,
initState: {}
});
const AppRoot = (
<ApolloProvider client={graph}>
<Provider store={store}>
<StaticRouter location={req.url} context={routerContext}>
<App />
</StaticRouter>
</Provider>
</ApolloProvider>
);
getDataFromTree(AppRoot)
.then(() => {
const preloadedState = store.getState();
const htmlSteam =
Template.header({
paths: { base: BASE_ROUTE, resources: RESOURCES_BASE_ROUTE }
}) +
renderToString(AppRoot) +
Template.footer({
config: {
paths: { base: BASE_ROUTE, resources: RESOURCES_BASE_ROUTE },
urls: {
graphql: EXTERNAL_URL_GRAPH,
events: EXTERNAL_URL_EVENTS
}
},
preloadedState,
preloadedGraphState: graph.extract()
});
if (routerContext.url) {
res.redirect(routerContext.url);
} else {
res.status(200);
res.send(htmlSteam);
}
})
.catch(function(error) {
console.log(error);
});
}
Example #22
Source File: server.js From react-keycloak-examples with MIT License | 5 votes |
server
.disable('x-powered-by')
.use(express.static(process.env.RAZZLE_PUBLIC_DIR))
.use(cookieParser()) // 1. Add cookieParser Express middleware
.get('/*', (req, res) => {
const context = {}
// 2. Create an instance of ServerPersistors.ExpressCookies passing the current request
const cookiePersistor = ServerPersistors.ExpressCookies(req)
// 3. Wrap the App inside SSRKeycloakProvider
const markup = renderToString(
<SSRKeycloakProvider
keycloakConfig={getKeycloakConfig()}
persistor={cookiePersistor}
>
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
</SSRKeycloakProvider>
)
if (context.url) {
res.redirect(context.url)
} else {
res.status(200).send(
`<!doctype html>
<html lang="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<title>Welcome to Razzle</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>window.env = ${JSON.stringify(getKeycloakConfig())}</script>
${
assets.client.css
? `<link rel="stylesheet" href="${assets.client.css}">`
: ''
}
${
process.env.NODE_ENV === 'production'
? `<script src="${assets.client.js}" defer></script>`
: `<script src="${assets.client.js}" defer crossorigin></script>`
}
</head>
<body>
<div id="root">${markup}</div>
</body>
</html>`
)
}
})
Example #23
Source File: server.js From react-workshop with MIT License | 5 votes |
server
.disable('x-powered-by')
.use(express.static(process.env.RAZZLE_PUBLIC_DIR))
.get('/*', (req, res) => {
const apolloClient = new ApolloClient({
ssrMode: true,
cache: new InMemoryCache(),
link: createHttpLink({
uri: 'https://asia-southeast2-minitokopedia.cloudfunctions.net/graphql',
}),
});
const context = {};
const markup = (
<ApolloProvider client={apolloClient}>
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
</ApolloProvider>
);
if (context.url) {
res.redirect(context.url);
} else {
getDataFromTree(markup).then((content) => {
const initialState = apolloClient.extract();
const html = renderToString(
<html lang="en">
<head>
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<title>Welcome to Razzle</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
{cssLinksFromAssets(razzleAssets, 'client')}
</head>
<body>
<div id="root" dangerouslySetInnerHTML={{ __html: content }} />
<script
dangerouslySetInnerHTML={{
__html: `window.__APOLLO_STATE__=${JSON.stringify(initialState).replace(/</g, '\\u003c')};`,
}}
/>
{jsScriptTagsFromAssets(razzleAssets, 'client')}
</body>
</html>,
);
res.status(200).header('Content-Type', 'text/html').send(`<!doctype html>\n${html}`);
});
}
});
Example #24
Source File: constructor-details.spec.js From horondi_admin with MIT License | 5 votes |
describe('constructor-details tests', () => {
beforeEach(() => {
wrapper = mount(
<StaticRouter
store={mockStore}
location='/constructor-model/60eadfb9e913fc288294bd9'
>
<Switch>
<Route
path='/constructor-model/:id'
exact
component={ConstructorModelDetails}
/>
</Switch>
</StaticRouter>
);
});
test('Should render constructor-details', () => {
expect(wrapper).toBeDefined();
});
test('Should render loading bar', () => {
useSelector.mockImplementation(() => ({
...mockStore,
loading: true
}));
wrapper = mount(
<StaticRouter
store={mockStore}
location='/constructor-model/60eadfb9e913fc288294bd9'
>
<Switch>
<Route
path='/constructor-model/:id'
exact
component={ConstructorModelDetails}
/>
</Switch>
</StaticRouter>
);
expect(wrapper.find(LoadingBar)).toBeDefined();
});
test('Should render constructor-details without model', () => {
useSelector.mockImplementation(() => ({ ...mockStore, model: null }));
wrapper = mount(
<StaticRouter store={mockStore} location='/constructor-model/1'>
<Switch>
<Route
path='/constructor-model/:id'
exact
component={ConstructorModelDetails}
/>
</Switch>
</StaticRouter>
);
expect(wrapper).toBeDefined();
});
});
Example #25
Source File: entry-server.jsx From reactplate with MIT License | 5 votes |
export function render(url, context) {
return renderToString(
<StaticRouter location={url} context={context}>
<App />
</StaticRouter>
);
}
Example #26
Source File: render.js From Learning-Redux with MIT License | 5 votes |
serverSideRendering = (indexFile, loadStaticFile) => (req, res) => {
const isIndexPage = req.url === "/" || req.url === "/index.html";
if (isIndexPage) {
if (cachedResult) return res.send(cachedResult);
}
console.log("server-side rendering started for", req.url);
const history = createHistory();
const store = configureStore({}, history, true);
return initStore(store)
.then(() => {
const context = {};
const markup = renderToString(
<Provider store={store}>
<StaticRouter
location={isIndexPage ? "/" : req.url}
context={context}
>
<App />
</StaticRouter>
</Provider>
);
const storeState = JSON.stringify(store.getState()).replace(
/</g,
"\\u003c"
);
const dom = new JSDOM(indexFile, { runScripts: "outside-only" });
dom.window.eval(`
document.getElementById('root').innerHTML = '${markup}'
`);
dom.window.eval(`
var script = document.createElement('script')
script.innerHTML = 'window.__PRELOADED_STATE__ = ${storeState}'
document.body.insertBefore(script,
document.getElementsByTagName('script')[0]
)
`);
if (isIndexPage) {
cachedResult = dom.serialize();
console.log("server-side rendering done, cached result");
if (res) return res.send(cachedResult);
} else {
console.log("server-side rendering done");
if (res) return res.send(dom.serialize());
}
})
.catch((err) => {
console.error("server-side rendering error:", err);
if (loadStaticFile) return loadStaticFile(req, res);
});
}
Example #27
Source File: server.js From module-federation-examples with MIT License | 4 votes |
export async function server(event, context) {
// const wrapped = performance.timerify(someFunction);
performance.mark(`initializeFederatedImports: start`);
await initializeFederatedImports({
s3Client,
federatedModules: federatedModules.default,
});
performance.mark(`initializeFederatedImports: end`);
const extraRouteMiddleware = (
await import('@streamed-federation/federated-middleware/extraRoute')
).default;
performance.mark(`extraRouteMiddleware: end`);
console.log('extraRouteMiddleware', extraRouteMiddleware);
performance.measure(
'initializeFederatedImports',
'initializeFederatedImports: start',
'initializeFederatedImports: end',
);
performance.measure(
'extraRouteMiddleware',
'initializeFederatedImports: end',
'extraRouteMiddleware: end',
);
performance.measure(
'Federation Timing',
'initializeFederatedImports: start',
'extraRouteMiddleware: end',
);
app.use('/federated', extraRouteMiddleware);
app.get('/*', (req, res) => {
const context = {};
const store = createStore();
store.dispatch(initializeSession());
const dataRequirements = routes
.filter(route => matchPath(req.url, route)) // filter matching paths
.map(route => route.component) // map to components
.filter(comp => comp.serverFetch) // check if components have data requirement
.map(comp => store.dispatch(comp.serverFetch())); // dispatch data requirement
Promise.all(dataRequirements).then(() => {
const jsx = (
<ReduxProvider store={store}>
<StaticRouter context={context} location={req.url}>
<Layout />
</StaticRouter>
</ReduxProvider>
);
const reactDom = ReactDomServer.renderToString(jsx);
const reduxState = store.getState();
const helmetData = Helmet.renderStatic();
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(htmlTemplate(reactDom, reduxState, helmetData));
});
});
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
function htmlTemplate(reactDom, reduxState, helmetData) {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
${helmetData.title.toString()}
${helmetData.meta.toString()}
<title>React SSR</title>
<link rel="stylesheet" type="text/css" href="./client.css" />
</head>
<body>
<div id="app">${reactDom}</div>
<script>
window.REDUX_DATA = ${serialize(reduxState, { isJSON: true })}
</script>
<script src="./client.js"></script>
</body>
</html>
`;
}
}
Example #28
Source File: server.js From Edlib with GNU General Public License v3.0 | 4 votes |
renderApp = async (req, res) => {
const context = {};
const emotionCache = createEmotionCache();
const sheet = new ServerStyleSheet();
const emotionServers = [
// Every emotion cache used in the app should be provided.
// Caches for MUI should use "prepend": true.
// MUI cache should come first.
emotionCache,
getTssDefaultEmotionCache({ doReset: true }),
].map(createEmotionServer);
const wwwUrl = `${req.protocol}://${req.get('host')}`;
const SetupApp = (initialState, promiseList = []) => (
<CacheProvider value={emotionCache}>
<ThemeProvider theme={muiTheme}>
<StaticRouter context={context} location={req.url}>
<FetchProvider
promiseList={promiseList}
initialState={initialState}
ssrCookies={res.getCookies()}
ssrAddCookiesFromSetCookie={res.addCookiesFromSetCookie}
>
<ConfigurationProvider
apiUrl={wwwUrl.replace('www', 'api')}
wwwUrl={wwwUrl}
isSSR
cookies={req.cookies}
>
<App />
</ConfigurationProvider>
</FetchProvider>
</StaticRouter>
</ThemeProvider>
</CacheProvider>
);
const maxDepth = 10;
const getStateFromTree = async (state = {}, depth = 0) => {
const promiseList = [];
renderToString(SetupApp(state, promiseList));
if (promiseList.length !== 0 && depth < maxDepth) {
await addPromiseListToState(state, promiseList);
return getStateFromTree(state, depth + 1);
}
return { state };
};
const { state } = await getStateFromTree();
const markup = renderToString(sheet.collectStyles(SetupApp(state, [])));
const helmet = Helmet.renderStatic();
// Grab the CSS from emotion
const styleTagsAsStr = emotionServers
.map(({ extractCriticalToChunks, constructStyleTagsFromChunks }) =>
constructStyleTagsFromChunks(extractCriticalToChunks(markup))
)
.join('');
// Grab the CSS from styled-components
const styledComponentsTags = sheet.getStyleTags();
const html = `<!doctype html>
<html lang="">
<head ${helmet.htmlAttributes.toString()}>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
${cssLinksFromAssets(assets, 'client')}
${styleTagsAsStr}
${styledComponentsTags}
${helmet.title.toString()}
${helmet.meta.toString()}
${helmet.link.toString()}
</head>
<body ${helmet.bodyAttributes.toString()}>
<script>
window.__FETCH_STATE__=${JSON.stringify(state).replace(
/</g,
'\\u003c'
)};
</script>
<div id="root">${markup}</div>
${jsScriptTagsFromAssets(assets, 'client', 'defer', 'crossorigin')}
</body>
</html>`;
return { context, html };
}
Example #29
Source File: load-routes.js From crate with MIT License | 4 votes |
export default function (app) {
console.info('SETUP - Load routes..')
// Store (new store for each request)
const store = createStore(
rootReducer,
applyMiddleware(thunk)
)
// Match any Route
app.get('*', (request, response) => {
// Check for auth
if (request.cookies.auth) {
const auth = JSON.parse(request.cookies.auth)
if (auth && auth.token !== '' && auth.user) {
store.dispatch(setUser(auth.token, auth.user))
}
}
// HTTP status code
let status = 200
const matches = Object.values(routes).reduce((matches, route) => {
const match = matchPath(request.url, typeof route.path === 'function' ? route.path() : route.path, route)
if (match && match.isExact) {
matches.push({
route,
match,
promise: route.component.fetchData ? route.component.fetchData({
store,
params: match.params
}) : Promise.resolve(null)
})
}
return matches
}, [])
// No such route, send 404 status
if (matches.length === 0) {
status = 404
}
// Any AJAX calls inside components
const promises = matches.map((match) => {
return match.promise
})
// Resolve the AJAX calls and render
Promise.all(promises)
.then((...data) => {
const initialState = store.getState()
const context = {}
const appHtml = renderToString(
<Provider store={store} key="provider">
<StaticRouter context={context} location={request.url}>
<App/>
</StaticRouter>
</Provider>
)
if (context.url) {
response.redirect(context.url)
} else {
// Get Meta header tags
const helmet = Helmet.renderStatic()
const styles = flushToHTML()
const html = view(APP_URL, NODE_ENV, helmet, appHtml, styles, initialState)
// Reset the state on server
store.dispatch({
type: 'RESET'
})
// Finally send generated HTML with initial data to the client
return response.status(status).send(html)
}
})
.catch(error => {
console.error(error)
})
})
}