Skip to content

Instantly share code, notes, and snippets.

@luandevpro
Created March 12, 2019 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luandevpro/466e00256930bcb146eb107ee92eca5b to your computer and use it in GitHub Desktop.
Save luandevpro/466e00256930bcb146eb107ee92eca5b to your computer and use it in GitHub Desktop.
import Document, { Head, Main, NextScript } from 'next/document'
// Import styled components ServerStyleSheet
import { ServerStyleSheet } from 'styled-components';
import { getServerSideToken, getUserScript } from '../auth';
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const page = ctx.renderPage((App) => (props) =>
sheet.collectStyles(<App {...props} />),
);
const styleTags = sheet.getStyleElement();
const userData = await getServerSideToken(ctx.req);
return { ...page, styleTags , ...userData};
}
render () {
var { user } = this.props
return (
<html>
<Head>
<title>My page</title>
{this.props.styleTags}
</Head>
<body>
<Main />
// chú ý chỗ này nhé
<NextScript />
<script dangerouslySetInnerHTML={{__html: getUserScript(user)}}/>
</body>
</html>
)
}
}
// auth/index.js
const WINDOW_USER = "__USER__"
export const loginUser = async (email, password) => {
const { data } = await axios.post("/api/login", { email , password});
if(typeof window !== undefined){
window[WINDOW_USER] = data || {}
}
}
export const getUserScript = (user) => {
return `${WINDOW_USER} = ${JSON.stringify(user)}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment