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