Skip to content

Instantly share code, notes, and snippets.

@Calvin-Huang
Created October 2, 2020 03:15
Show Gist options
  • Save Calvin-Huang/dbc5e56df1fc0f2963161fcc1ea8907c to your computer and use it in GitHub Desktop.
Save Calvin-Huang/dbc5e56df1fc0f2963161fcc1ea8907c to your computer and use it in GitHub Desktop.
The sample which works fine without any shared state problems.
/* /page/home.jsx */
import { getAxios } from '@util/axios'
const Home = ({ user }) => {
return (
<h1>{user.name}</h1>
)
}
Home.getServerSideProps = async ({ req }) => {
// Set shared cookie for
const token = Cookies.new(req.headers.cookie).get('user-token')
const { data } = await getAxios(token).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 getAxios = (token = Cookies.shared.get('user-token')) => {
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 ${token}`,
...config.headers,
}
return config
})
return axios
}
export default const defaultAxios = getAxios()
------
/* /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