Last active
October 2, 2020 03:17
-
-
Save Calvin-Huang/97cdbd53457fc7afa7d6b1b6e5d68e87 to your computer and use it in GitHub Desktop.
Get user's credential before rendering to prevent showing empty username.
This file contains hidden or 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
/* /page/home.jsx */ | |
import axios from '@util/axios' | |
const Home = ({ user }) => { | |
return ( | |
<h1>{user.name}</h1> | |
) | |
} | |
Home.getServerSideProps = async ({ req }) => { | |
// Set shared cookie for | |
Cookies.shared = Cookies.new(req.headers.cookie) | |
const { data } = await axios.get('https://mock.bugfree.app/api/me') | |
return { | |
props: { | |
user: data, | |
}, | |
} | |
} | |
export default Home | |
------ | |
/* /util/axios.js */ | |
import Cookies from './cookie' | |
import originalAxios from 'axios' | |
export const axios = originalAxios.create() | |
// Customized axios with interceptor to add Authorization content to header for every requests. | |
axios.interceptors.request.use(config => { | |
config.headers = { | |
authorization: `Bearer ${Cookies.shared.get('user-token')}`, | |
...config.headers, | |
} | |
return config | |
}) | |
export default axios | |
------ | |
/* /util/cookie.js */ | |
import Cookies from 'universal-cookie' | |
export const cookie = { | |
new(cookieString) { | |
return new Cookies(cookieString) | |
}, | |
set shared(value) { | |
this._cookie = value | |
}, | |
get shared() { | |
if (!this._cookie) { | |
this._cookie = new Cookies() | |
} | |
return this._cookie | |
}, | |
} | |
export default cookie |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment