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?

【React】Reactでバックエンド(Express)からCookieを送信し、ブラウザに保存

Last updated at Posted at 2025-05-06

ゴール

ログイン用APIでExpressに問い合わせ、そのレスポンスにCookieを含めてブラウザに登録できることを確認する。

クライアント:React上のFetchAPI
サーバーサイド:Express

クライアント側

FetchAPIでは、下記のように記載

    const response = await fetch(url,{
        method: 'POST',
        headers: {                
                    'Origin': 'http://localhost:3000',
                    'Content-Type': 'application/json',
                },
        credentials: 'include', // クッキーを許可するために必須
        body: userAuthJson
        })

credentials: 'include' でCookieの送受信を許可する

サーバーサイド側

レスポンスヘッダーに'Access-Control-Allow-Credentials', 'true'が必要

//cors対応
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Origin, X-Csrftoken, Content-Type');
    res.header('Access-Control-Allow-Credentials', 'true');  // クッキーを送信するために必須
    next();
  }


app.use(allowCrossDomain);
app.use(express.json());

app.post('/userauth', (req, res) => {
  console.log(req.body);
  res.cookie('token', 'abc123', {
    httpOnly: true,   // JSから読み取れない → セキュリティ強
    //secure: true,     // HTTPSのみ
    maxAge: 3600000,  // 1時間
    sameSite: 'lax'
  });

httpOnly : JavaScriptでCookieを取得できない(XSSやセッションハイジャック対策)
secure : Https通信以外ではCookie使用不可(盗聴防止)
sameSite : Strictだと同一オリジンのみでCookie送信可能

今回は検証のため、あくまでabc123という固定値をCookieに使用したがセッションIDやJWTを使用するのが正しい

APIを叩いてブラウザのCookieを確認する

『開発者ツール』⇒『Application』⇒『Cookie』
内で対象のドメインを確認
image.png
↑作成されている

Cookieについて

Cookieにはドメイン情報が付加されているため、一度発行されると自動的にサーバー側に送信されるようになる。

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?