From 62b2cd2f4a06a2b67d2d9532a90322904599cb98 Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Sun, 19 Aug 2018 14:21:23 +0300 Subject: [PATCH] Use Helmet with SSR --- src/index.html.ejs | 3 --- src/routes.tsx | 17 +++++++++++++---- src/server/index.ts | 10 ++++++++-- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/index.html.ejs b/src/index.html.ejs index 2f259c9..c8a9e19 100644 --- a/src/index.html.ejs +++ b/src/index.html.ejs @@ -2,9 +2,6 @@ - - - Aalto-yliopiston Sähköinsinoorikilta ry
diff --git a/src/routes.tsx b/src/routes.tsx index 0ea8ce7..9227fa2 100644 --- a/src/routes.tsx +++ b/src/routes.tsx @@ -1,15 +1,24 @@ import * as React from "react"; +import { Fragment } from "react"; import { Switch, Route } from "react-router-dom"; +import Helmet from "react-helmet"; import FrontPage from "./pages/FrontPage"; import NotFoundPage from "./pages/NotFoundPage"; import CommonPage from "./pages/CommonPage"; import "./index.scss"; const Routes = () => ( - - } /> - - + + + Aalto-yliopiston Sähköinsinoorikilta ry + + + + + } /> + + + ); export default Routes; diff --git a/src/server/index.ts b/src/server/index.ts index f9730fe..16a9e60 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,4 +1,5 @@ import * as React from "react"; +import Helmet from "react-helmet"; import * as express from "express"; import { renderToString } from "react-dom/server"; import * as morgan from "morgan"; @@ -13,7 +14,11 @@ const port = 3000; const server = express(); const indexHtml = fs.readFileSync(path.resolve("./dist/index.html"), "utf-8"); -const html = body => indexHtml.replace("
", `
${body}
`); +const html = (body, title, meta) => { + const withBody = indexHtml.replace("
", `
${body}
`); + const withHead = withBody.replace("", `${title}${meta}`); + return withHead; +}; server.use(morgan("short")); server.use(helmet()); @@ -24,8 +29,9 @@ server.use("/js", express.static("dist/js")); server.get("*", (req, res) => { const result = renderToString(React.createElement(App, { url: req.url })); + const head = Helmet.rewind(); res.send( - html(result) + html(result, head.title, head.meta) ); });