Created
March 12, 2019 09:38
-
-
Save luandevpro/466e00256930bcb146eb107ee92eca5b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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