我有一个基于Redux的Next.js应用程序,具有基于jwt的身份验证。 jwt令牌是由rails api生成的,并且被设置为Next.js服务器与浏览器之间的cookie,因此需要将其包含在对rails api的任何请求的标头中。
对Rails api的请求可以直接从浏览器发出,也可以在呈现页面组件时从Next.js服务器发出。为了便于在标头中注入令牌,我将用于发送请求的逻辑封装在名为Api.js
的非组件文件中。唯一的挑战是,哪里是存储jwt令牌的最佳位置,因此无论在何处(浏览器或Next.js服务器)运行它,Api.js
都可以对其进行访问
我按照以下步骤解决了这个问题:
class Api {
constructor () {
if (!Api.instance) { Api.instance = this; }
return Api.instance;
}
setReduxStore(reduxStore) {
this.reduxStore = reduxStore;
}
getReduxStore() {
return this.reduxStore;
}
getIdToken(){
return deepRead(this.getReduxStore().getState(), 'session.idToken');
}
backendSend(options) {
return axios({
method: options.method,
url: options.url,
data: options.data,
headers: {
...options.headers,
Authorization: this.getIdToken()
}
});
}
}
const instance = new Api();
export default instance;
reduxStore
传递给_app.js
中的Api:static async getInitialProps({ Component, ctx }) {
const isServer = typeof ctx.req !== 'undefined';
if (isServer) {
Api.setReduxStore(ctx.reduxStore);
}
// ...
}
componentDidMount() {
// runs only on browser
Api.setReduxStore(this.props.reduxStore);
}
现在我担心下面的比赛情况,并且不确定下面的情况是否会发生?
Api
是用用户B的reduxStore初始化的。