Skip to content
This repository has been archived by the owner on Jan 2, 2018. It is now read-only.

Commit

Permalink
Merge pull request #51 from rocjs/feature/ssr-redirects
Browse files Browse the repository at this point in the history
Support redirects on the server side triggered by history modifications
  • Loading branch information
dlmr authored Dec 3, 2016
2 parents 2b96af1 + 10606d1 commit 6007a79
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ export default function createClient({ createRoutes, createStore, mountNode }) {
}

let routes;
let locals = {};
let locals = {
history,
};
const createComponent = [(component) => component];
const createDevComponent = [(component) => component];

Expand All @@ -117,6 +119,7 @@ export default function createClient({ createRoutes, createStore, mountNode }) {
locals = {
dispatch: store.dispatch,
getState: store.getState,
history,
};

createComponent.push((component) => (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,21 @@ export function reactRender({
reduxSagas,
}) {
return new Promise((resolve) => {
let currentLocation;

history.listen((location) => {
currentLocation = location;
});

match({ history, routes: createRoutes(store), location: url },
(error, redirect, renderProps) => {
if (redirect) {
log(`Redirect request to ${redirect.pathname + redirect.search}`);
const base = redirect.basename || '';
const redirectUrl = `${base}${redirect.pathname}${redirect.search}`;
log(`Redirect request to ${redirectUrl} due to React Router`);

return resolve({
redirect: redirect.pathname + redirect.search,
redirect: redirectUrl,
});
} else if (error) {
log('Router error', pretty.render(error));
Expand All @@ -106,7 +115,10 @@ export function reactRender({
const locals = store ? {
dispatch: store.dispatch,
getState: store.getState,
} : {};
history,
} : {
history,
};

const hooks = rocConfig.runtime.fetch.server;

Expand All @@ -126,6 +138,20 @@ export function reactRender({
}
return result;
}).then(({ redialMap, redialProps }) => {
if (currentLocation) {
const currentUrl = `${currentLocation.pathname}${currentLocation.search}`;

if (currentUrl !== url) {
const base = currentLocation.basename || '';
const redirectUrl = `${base}${currentUrl}`;

log(`Redirect request to ${redirectUrl} due to history location modification`);
return resolve({
redirect: `${redirectUrl}`,
});
}
}

let component = applyRouterMiddleware(useRedial({ redialMap }))(renderProps);

if (store) {
Expand Down

0 comments on commit 6007a79

Please sign in to comment.