Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSR functionality #258

Open
wants to merge 2 commits into
base: ssr
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions .env.default
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@
BACKEND_URL=http://localhost:8000

# where to proxy PROXY paths
# (userful for not SPA, when you need to proxy API but get templates from local backend)
# userful for not SPA, when you need to proxy API but get templates from local backend
PROXY_URL=$BACKEND_URL

# server side rendering
# enable to proxy all requests to BACKEND_URL (except frontend assets)
# userful for react SSR or MPA (multi-page applications)
SSR=
# disable for proxy all requests to BACKEND_URL (except frontend assets)
# userful for non-SPA applications, CMS or MPA (multi-page applications)
# to disable just remove the value, e.g `SPA=`
SPA=

# enable server side rendering
# ssr bundle and server will be available in dist/ssr
# to disable just remove the value, e.g `SSR=`
# WARNING! This will not work for non-SPA applications.
SSR=true
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we need to make SPA=true and SSR=?


# subdomain feature
MAIN_HOST=localhost
Expand Down Expand Up @@ -36,7 +42,7 @@ DEV_SERVER_PORT=3000
DEV_SERVER_HOST=127.0.0.1

# proxy paths for dev server ( note that API_URL will be added automatically to this array )
PROXY=["${API_URL}", "/static/", "/media/"]
PROXY=["${API_URL}", "/static/", "/media/", "/jsi18n/"]

# key for store redux state in localStorage
STORAGE_KEY=$APP_NAME
Expand Down
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
"keyword-spacing": ["error", { "overrides": {
"if": { "after": false },
"for": { "after": false },
"while": { "after": false }
"while": { "after": false },
"catch": { "after": false }
}}],
"spaced-comment": ["error", "always", {
"line": { "exceptions": ["/"], "markers": ["/"] },
Expand Down
5 changes: 5 additions & 0 deletions init-env.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,10 @@ const configDefault = dotenv.config({
dotenvExpand(config)
dotenvExpand(configDefault)

if(!Boolean(process.env.SPA) && Boolean(process.env.SSR)) {
console.warn('!!! SSR is disabled for non SPA applications !!!')
// set APP_NAME from package.json
process.env.SSR = ''
}

export default process.env
16 changes: 10 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
"repository": "github:django-stars/frontend-skeleton",
"scripts": {
"start": "NODE_ENV=development webpack-dev-server --progress --colors --mode development",
"start:web": "SSR= NODE_ENV=development webpack-dev-server --progress --colors --mode development --config-name web",
"build": "NODE_ENV=production webpack --mode production",
"ssr": "node src/ssr/index.js",
"lint": "yarn run eslint && yarn run stylelint",
"lint:fix": "yarn run eslint:fix && yarn run stylelint:fix",
"eslint": "node linter --verbose | snazzy",
Expand All @@ -38,19 +40,21 @@
"bootstrap": "^4.0.0",
"core-decorators": "^0.20.0",
"ds-frontend": "https://github.com/django-stars/ds-frontend.git#9dbaa21",
"express": "^4.17.1",
"lodash": "^4.17.15",
"node-fetch": "^2.6.1",
"path-to-regexp": "^6.1.0",
"prop-types": "^15.7.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-helmet": "^6.1.0",
"react-redux": "^7.2.0",
"react-router": "^5.1.2",
"react-router-dom": "^5.1.2",
"redux": "^4.0.5",
"redux-devtools-extension": "^2.13.8",
"redux-sentry-middleware": "^0.1.3",
"reselect": "^4.0.0",
"smoothscroll-polyfill": "^0.4.3",
"whatwg-fetch": "^3.0.0"
},
"devDependencies": {
Expand All @@ -76,6 +80,7 @@
"babel-plugin-react-require": "^3.1.1",
"clean-webpack-plugin": "^3.0.0",
"core-js": "3",
"decache": "^4.6.0",
"dotenv": "^6.0.0",
"dotenv-expand": "^5.1.0",
"enzyme": "^3.3.0",
Expand All @@ -94,20 +99,19 @@
"jest-cli": "^24.1.0",
"jest-enzyme": "^7.0.1",
"lint-staged": "^9.4.3",
"null-loader": "^4.0.1",
"postcss-inline-svg": "^3.0.0",
"react-hot-loader": "^4.12.19",
"react-test-renderer": "^16.8.3",
"redux-mock-store": "^1.5.1",
"reload-html-webpack-plugin": "^0.1.2",
"snazzy": "^8.0.0",
"standard-engine": "^10.0.0",
"stylelint": "^10.1.0",
"stylelint-config-standard": "^18.3.0",
"stylelint-scss": "^3.9.0",
"webpack": "^4.29.6",
"webpack-blocks": "^2.0.0-rc",
"webpack-cli": "^3.2.3",
"webpack-dev-server": "^3.2.1",
"write-file-webpack-plugin": "^4.5.0"
"webpack-blocks": "^2.1.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
}
4 changes: 2 additions & 2 deletions presets/assets.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { file, group, match } from 'webpack-blocks'

export default function(config) {
export default function assets(config = {}) {
return group([
// will copy font files to build directory and link to them
match(['*.eot', '*.ttf', '*.woff', '*.woff2', '*.png', '*.jpg', '*.svg'], [
file(),
file({ emitFile: !config.ssr }),
]),
])
}
70 changes: 70 additions & 0 deletions presets/dev-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { group, devServer as devServerBlock } from 'webpack-blocks'
import path from 'path'
import get from 'lodash/get'
import { getFilenameFromUrl } from 'webpack-dev-middleware/lib/util'
import { match as proxyMatch } from 'http-proxy-middleware/lib/context-matcher'
import getContent from '../src/ssr/get-content'
import decache from 'decache'


const publicPath = path.resolve(`${process.env.OUTPUT_PATH}`)

export default function devServer() {
return devServerBlock({
contentBase: path.resolve(`${process.env.OUTPUT_PATH}`),
port: process.env.DEV_SERVER_PORT || 3000,
overlay: true,
clientLogLevel: 'info', // FIXME move to VERBOSE mode (add loglevel/verbose option)
stats: 'minimal',
host: process.env.DEV_SERVER_HOST,

// FIXME
filename: 'bundle.js',

allowedHosts: [
'.localhost',
`.${process.env.MAIN_HOST}`,
],

writeToDisk: true,

before: middleware,
})
}

function middleware(app, server, compiler) {
app.get('*', function(req, res, next) {
if(!process.env.SSR) {
return next()
}

let accept = String(get(req, 'headers.accept', ''))
Copy link
Contributor

@NikitaMazur NikitaMazur Dec 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where do you use this variable?


let isWebpackAsset = getFilenameFromUrl(
Copy link
Contributor

@NikitaMazur NikitaMazur Dec 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const

process.env.PUBLIC_PATH,
compiler,
req.url
)

let isProxyMatched = proxyMatch(
Copy link
Contributor

@NikitaMazur NikitaMazur Dec 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const

JSON.parse(process.env.PROXY),
req.originalUrl || req.url,
req
)

// skip
if(isWebpackAsset || isProxyMatched) {
return next()
}

// run SSR
// TODO ensure that compilation is completed
decache('../dist/ssr/ssr')
return getContent(req.url)
.then(c => res.send(c.content))
.catch(e => {
res.status(500).send('Internal server error.')
console.error(e)
})
})
}
5 changes: 5 additions & 0 deletions presets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import assets from './assets'
import proxy from './proxy'
import sentry from './sentry'
import i18n from './i18n'
import ssr from './ssr'
import devServer from './dev-server'


export {
babel,
Expand All @@ -20,4 +23,6 @@ export {
proxy,
sentry,
i18n,
ssr,
devServer,
}
2 changes: 1 addition & 1 deletion presets/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function configureProxy() {
makeProxyContext(JSON.parse(process.env.PROXY), process.env.PROXY_URL),
]

if(process.env.SSR) {
if(!process.env.SPA) {
// proxy templates
ret.push(
makeProxyContext([
Expand Down
6 changes: 2 additions & 4 deletions presets/react.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { group, babel } from 'webpack-blocks'


export default function(config) {
export default function({ ssr = false } = {}) {
return group([
babel({
presets: [
Expand All @@ -11,9 +11,7 @@ export default function(config) {

plugins: [
'babel-plugin-react-require',
// need for react HMR
// 'extract-hoc/babel',
'react-hot-loader/babel',
...(ssr ? [] : ['react-hot-loader/babel']),
],
}),

Expand Down
34 changes: 34 additions & 0 deletions presets/ssr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { group, match, devServer, env, addPlugins } from 'webpack-blocks'
import path from 'path'
import webpack from 'webpack'

export default function ssr(config) {

return group([
match(['*.css', '*.sass', '*.scss', '*polyfills.js'], [
nothing(),
]),

/*
env('development', [
devServer({
inline: false,
// FIXME hot updates still created
hot: false,
})
]),
*/
])
}

function nothing(options = {}) {
return (context, util) =>
util.addLoader(
Object.assign(
{
use: 'null-loader',
},
context.match
)
)
}
14 changes: 8 additions & 6 deletions presets/styles.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ export default function(config) {
// path.resolve will provide incorrect string, so we need to use RegExp here
// more documentation here: https://webpack.js.org/configuration/module/#condition
match(['*.css', '*.sass', '*.scss'], { exclude: /node_modules/ }, [
process.env.SSR ? css() : css.modules({ camelCase: true }),
css.modules({ localsConvention: 'camelCaseOnly' }),
sass({
includePaths: [
path.resolve('./src/styles'),
path.resolve('./node_modules/bootstrap/scss'),
path.resolve('./node_modules'),
],
sassOptions: {
includePaths: [
path.resolve('./src/styles'),
path.resolve('./node_modules/bootstrap/scss'),
path.resolve('./node_modules'),
],
}
}),
postcss(),
env('production', [
Expand Down
48 changes: 36 additions & 12 deletions src/app/App.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,48 @@
import { Fragment } from 'react'
import { Provider } from 'react-redux'
import { Router } from 'common/router'
import { CheckCache } from '@ds-frontend/cache'
import { hot } from 'react-hot-loader/root'
import routes from './routes'
import PropTypes from 'prop-types'

AppProvider.propTypes = {
App.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
routerContext: PropTypes.object,
origin: PropTypes.string,
staticUrl: PropTypes.string,
}

App.defaultProps = {
routerContext: {},
origin: undefined,
staticUrl: undefined,
}


function AppProvider({ store, history }) {
return (
<Provider store={store}>
<CheckCache>
<Router history={history} routes={routes}/>
</CheckCache>
</Provider>
)
function App({ store, staticUrl, origin, routerContext }) {
try {
const CheckCacheComponent = process.env.SSR ? Fragment : CheckCache
return (
<Provider store={store}>
<CheckCacheComponent>
<Router staticUrl={staticUrl} origin={origin} routerContext={routerContext} routes={routes}/>
</CheckCacheComponent>
</Provider>
)
} catch(error) {
// TODO log to sentry
console.error('[e][%s] render', process.env.SSR ? 'SSR' : 'SPA ⬇️')
console.error(error)
return (
<Fragment>
{process.env.SSR && (
<h2>500</h2>
)}
<p>Something went wrong.</p>
<p>Please try to reload the page or go to <a href="/">home</a></p>
</Fragment>
)
}
}

export default hot(AppProvider)
export default process.env.SSR ? App : require('react-hot-loader/root').hot(App)
Loading