Add example of isomorphic cookies for #581

This commit is contained in:
SteveSandersonMS
2017-01-16 12:54:44 +00:00
parent f8714e9653
commit 9c9892ab18
5 changed files with 54 additions and 5 deletions

View File

@@ -6,9 +6,28 @@ import createMemoryHistory from 'history/lib/createMemoryHistory';
import { createServerRenderer, RenderResult } from 'aspnet-prerendering';
import routes from './routes';
import configureStore from './configureStore';
import cookieUtil from 'cookie';
import cookie from 'react-cookie';
function plugInCookiesFromDotNet(cookieData: { key: string, value: string }[], res) {
const formattedData = {};
cookieData.forEach(keyValuePair => {
formattedData[keyValuePair.key] = keyValuePair.value;
});
cookie.plugToRequest({ cookies: formattedData }, res);
}
export default createServerRenderer(params => {
return new Promise<RenderResult>((resolve, reject) => {
const cookiesModifiedOnServer = {};
if (params.data.cookies) {
// If we received some cookie data, use that to prepopulate 'react-cookie'
plugInCookiesFromDotNet(params.data.cookies, {
// Also track any cookies written on the server
cookie: (name, val) => { cookiesModifiedOnServer[name] = val; }
})
}
// Match the incoming request against the list of client-side routes
match({ routes, location: params.location }, (error, redirectLocation, renderProps: any) => {
if (error) {
@@ -42,7 +61,17 @@ export default createServerRenderer(params => {
params.domainTasks.then(() => {
resolve({
html: renderToString(app),
globals: { initialReduxState: store.getState() }
globals: {
initialReduxState: store.getState(),
// Send any cookies written during server-side prerendering to the client.
// WARNING: Do not pass any security-sensitive cookies this way, because they will become
// readable in the HTML source. If your goal is to use this approach to manage authentication
// cookies, then be sure *not* to use 'globals' to send them to the client - instead, invoke
// Microsoft.AspNetCore.SpaServices.Prerendering.Prerender directly from your .NET code and
// only send the 'html' part back to the client (or at least, not all of the 'globals').
cookieData: cookiesModifiedOnServer
}
});
}, reject); // Also propagate any errors back into the host application
});