How to handle auth token when doing SSR with next.js?

Viewed 626

I want to find a way to inject user api_token on the server side.

When doing ssr, I come to a situation that I need to fetch data of authenticated user.

On client-side, "data fetching" is start with redux-thunk and handled by an axios client (a global instance with some basic config), and api_token is attached by "express" with 'http-proxy-middleware'.

On server-side, the axios client does not contain any auth related info. It seems that I need to initialize an axios client in each request cycle on server side and modify all my 'redux-thunk-data-fetching' actions to use axios client passed through 'redux-thunk-extra-args'.

I wonder if there is a better way to handle this situation.

Example:

// request is an axios instance with basic config.
// api_token is auto handle by proxy-middleware if the request is from client side.
const fetchUserInfo = (userId) => request(`/api/to/get/user-info/${userId}`); 

// redux-thunk action
const asyncFetchUserInfo = (payload) => async (dispatch) => {
  const data = await fetchUserInfo(payload.userId);
  dispatch(loadUserInfo(data));
}

class UserPage extends React.Component {
  render() {
    return <div>Example Page</div>
  }
}

UserPage.getInitialProps = async ({ store, req }) => {
  const userInfo = await store.dispatch(asyncFetchUserInfo({ userId: req.userId }));
  return { userInfo }
}

Project sturcture:

[ client ] --> [ express(nodejs) ] --> [ api-server ]

  1. client
    • React + Redux + redux-thunk + axios
  2. An express server
    • do SSR with next.js
    • manage cookie-session with Redis ( user api_token is stored in session)
    • handle api proxy from browser (add auth headers based on session info)
0 Answers
Related