0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AxiosのInterceptorsを利用してAPIコール時のCookieセットを共通化する

Posted at

はじめに

こんにちは、H×Hのセンリツ大好きエンジニアです。(同担OKです😉)

Next.jsのServer Actions経由でJWTを用いた認証エンドポイントにリクエストする際、Server Actionsで認証エンドポイント毎にCookieをセットするのが大変だったのでAxios Interceptorsを使ってCookieのセットを共通化しました!

その方法をご共有しようと思います!

Axios Interceptorsとは

簡単に言うと、Axiosでのリクエストやレスポンスが処理される前に、処理を間に挟むことができる機能になります!

これを用いることで、APIをコールする際に共通して同じ処理を実行する事が出来たり、レスポンスのステータスによって共通の処理を実行する事が可能となります!

JWTを扱う場合ですと、access_tokenrefresh_tokenをCookieにセットして認証エンドポイントをコールする時にCookieからトークンを渡すような処理がありますが、そちらを共通してリクエスト前に行う使い方が可能です!

実装

基本的には、リクエストでインターセプターを利用する際以下のように記述します。

api.ts
// リクエスト インターセプターを追加します
axios.interceptors.request.use(function (config) {
    // リクエストが送信される前の処理
    return config;
  }, function (error) {
    // リクエスト エラーの処理
    return Promise.reject(error);
  });

こちらのリクエストが送信される前の処理内に、cookieを取得してリクエストのヘッダー内にセットしていきます!
今回はNext.jsを利用していますが、Cookieのセットはそれぞれのやり方で行ってください!

api.ts
import { cookies } from "next/headers";

axios.interceptors.request.use(function (config) {
    // リクエストが送信される前の処理
    const cookieHeader = [];
    // access_tokenとrefresh_tokenをそれぞれ格納していく
    const access_token = cookies.get("access_token");
    if (access_token) {
        cookieHeader.push(`${access_token.name}=${access_token.value}`)
    }

    const refresh_token = cookies.get("refresh_token");
    if (refresh_token) {
        cookieHeader.push(`${refresh_token.name}=${refresh_token.value}`)
    }

    // トークンが存在する場合はリクエストのヘッダーにセット
    if (cookieHeader.length > 0) {
        config.headers["Cookie"] = cookieHeader.join("; ")
    }
    return config;
  }, function (error) {
    // リクエスト エラーの処理
    return Promise.reject(error);
  });

上記のようにすると、Axiosを使う場合に共通してCookieをリクエストヘッダーにセットする処理を挿入する事が出来ます!

また、レスポンス時にaccess_tokenが無いことによる認証エラーが発生した場合に、refresh_tokenを用いてリフレッシュを行うことも共通化できます!

api.ts
// リクエスト インターセプターを追加します
axios.interceptors.response.use(function (response) {
    // ステータスコードが 2xx の範囲にある場合、この関数が起動します
    // リクエスト データの処理
    return response;
  }, 
  async function (error) {
    // ステータスコードが 2xx の範囲外の場合、この関数が起動します
    // リクエスト エラーの処理

    // JWTのリフレッシュAPI
    const res = await refresh_jwt();
    // 正常終了以外はログイン画面へ飛ばす
    if (res.status !== 200) {
        redirect("/login")
    }

    // 成功時はCookieにトークンをセットする処理を記述
    
    return Promise.reject(error);
  });

今回の例のように、Server Actionsだと直接クライアントにCookieがセットされないため、Axios Interceptorsを利用して共通化しちゃいましょう!

おわりに

今回はAxios InterceptorsでCookieをセットする処理の共通化についてご紹介しました!

ここまで書いておいてあれですが、Server ActionsでCookieを扱うと二度手間になってしまうのでRoute Handlerを活用するのも良い気がしました。

最後までご覧いただきありがとうございました🙇

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?