Next.js服务器是同时处理页面加载请求还是一次处理一个页面加载请求?

时间:2020-08-11 16:40:52

标签: concurrency next.js server-side-rendering

我有一个基于Redux的Next.js应用程序,具有基于jwt的身份验证。 jwt令牌是由rails api生成的,并且被设置为Next.js服务器与浏览器之间的cookie,因此需要将其包含在对rails api的任何请求的标头中。

对Rails api的请求可以直接从浏览器发出,也可以在呈现页面组件时从Next.js服务器发出。为了便于在标头中注入令牌,我将用于发送请求的逻辑封装在名为Api.js的非组件文件中。唯一的挑战是,哪里是存储jwt令牌的最佳位置,因此无论在何处(浏览器或Next.js服务器)运行它,Api.js都可以对其进行访问

我按照以下步骤解决了这个问题:

  • 使用redux存储jwt令牌
  • 使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);
}

现在我担心下面的比赛情况,并且不确定下面的情况是否会发生?

  • 来自用户A的页面加载请求到达了nextjs服务器,并且使用用户A的reduxStore初始化了Api
  • 来自用户B的页面加载请求到达了nextjs服务器,并且使用用户B的reduxStore初始化了Api
  • 用户A的页面加载请求继续进行后端请求,并使用用户B的jwt令牌,因为Api是用用户B的reduxStore初始化的。

0 个答案:

没有答案