Skip to content

Instantly share code, notes, and snippets.

@ashour
Created February 28, 2020 16:18
Show Gist options
  • Save ashour/8f8ccf8abdf7fee3470d51d13324d722 to your computer and use it in GitHub Desktop.
Save ashour/8f8ccf8abdf7fee3470d51d13324d722 to your computer and use it in GitHub Desktop.
import React from "react";
import express from "express";
import { StaticRouter } from "react-router-dom";
import { renderToString } from "react-dom/server";
import App from "./common/App";
import render from "./server/render";
import { determineUserLang } from "./common/i18n";
const server = express();
server
.disable("x-powered-by")
.use(express.static(process.env.RAZZLE_PUBLIC_DIR))
.get("/*", (req, res) => {
const context = {};
const lang = determineUserLang(req.acceptsLanguages(), req.path);
if (req.path.trim() === "/") {
res.redirect(`/${lang}`);
}
const markup = renderToString(
<StaticRouter context={context} location={req.url} basename={`/${lang}`}>
<App lang={lang} />
</StaticRouter>,
);
if (context.url) {
res.redirect(context.url);
} else {
const html = render(markup);
res.status(200).send(html);
}
});
export default server;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment