|
| 1 | +--- |
| 2 | +title: セッション |
| 3 | +description: オンデマンドレンダリングページのリクエスト間でデータを共有するための方法。 |
| 4 | +i18nReady: true |
| 5 | +--- |
| 6 | + |
| 7 | +import Since from '~/components/Since.astro'; |
| 8 | +import ReadMore from '~/components/ReadMore.astro'; |
| 9 | + |
| 10 | +<p> |
| 11 | +<Since v="5.7.0" /> |
| 12 | +</p> |
| 13 | + |
| 14 | +セッションは、[オンデマンドレンダリングページ](/ja/guides/on-demand-rendering/)のリクエスト間でデータを共有するための方法です。 |
| 15 | + |
| 16 | +[`cookies`](/ja/guides/on-demand-rendering/#クッキー)とは異なり、セッションはサーバーでデータを保存するため、より大きなデータを保存することができます。また、サイズ制限やセキュリティの問題も気にする必要がありません。ユーザーのデータ、ショッピングカート、フォームの状態などを保存するのに便利です。クライアント側のJavaScriptを使わないで機能します。 |
| 17 | + |
| 18 | +```astro title="src/components/CartButton.astro" {3} |
| 19 | +--- |
| 20 | +export const prerender = false; // 'server'出力の場合は不要 |
| 21 | +const cart = await Astro.session?.get('cart'); |
| 22 | +--- |
| 23 | +
|
| 24 | +<a href="/checkout">🛒 {cart?.length ?? 0} 点</a> |
| 25 | +``` |
| 26 | + |
| 27 | +## セッションの設定 |
| 28 | + |
| 29 | +セッションデータを保存するにはストレージドライバーが必要です。[Node](/ja/guides/integrations-guide/node/#sessions)・[Cloudflare](/ja/guides/integrations-guide/cloudflare/#セッション)・[Netlify](/ja/guides/integrations-guide/netlify/#sessions) の各アダプターはデフォルトドライバーを自動的に設定します。しかし、その他のアダプターでは [ドライバーを手動で指定](/ja/reference/configuration-reference/)する必要があります。 |
| 30 | + |
| 31 | +```js title="astro.config.mjs" ins={4} |
| 32 | + { |
| 33 | + adapter: vercel(), |
| 34 | + session: { |
| 35 | + driver: "redis", |
| 36 | + }, |
| 37 | + } |
| 38 | +``` |
| 39 | + |
| 40 | +<ReadMore> |
| 41 | + ストレージドライバーの設定方法やその他の設定項目の詳細については、[session設定オプション](/ja/reference/configuration-reference/)を参照してください。 |
| 42 | +</ReadMore> |
| 43 | + |
| 44 | +## セッションデータを操作する |
| 45 | + |
| 46 | +[`session`オブジェクト](/ja/reference/api-reference/#session) を使うと、保存されているユーザー状態(例:ショッピングカートへの商品の追加)やセッションID(例:ログアウト時にセッションID Cookieを削除)を操作できます。このオブジェクトはAstroのコンポーネントおよびページでは`Astro.session`として、APIエンドポイント・ミドルウェア・アクションでは`context.session`として利用できます。 |
| 47 | + |
| 48 | +セッションは初回利用時に自動生成され、[`session.regenerate()`](/ja/reference/api-reference/#regenerate)でいつでも再生成でき、[`session.destroy()`](/ja/reference/api-reference/#destroy)で破棄できます。 |
| 49 | + |
| 50 | +ほとんどの場合は、[`session.get()`](/ja/reference/api-reference/#get)と[`session.set()`](/ja/reference/api-reference/#set)の2つだけで十分です。 |
| 51 | + |
| 52 | +<ReadMore> |
| 53 | + 詳しくは [Sessions APIリファレンス](/ja/reference/api-reference/#session)を参照してください。 |
| 54 | +</ReadMore> |
| 55 | + |
| 56 | +### Astroコンポーネントとページ |
| 57 | + |
| 58 | +`.astro`コンポーネントやページでは、グローバル`Astro`オブジェクト経由でセッションにアクセスできます。たとえば、ショッピングカート内の商品数を表示する例です。 |
| 59 | + |
| 60 | +```astro title="src/components/CartButton.astro" "Astro.session" |
| 61 | +--- |
| 62 | +export const prerender = false; // 'server'出力の場合は不要 |
| 63 | +const cart = await Astro.session?.get('cart'); |
| 64 | +--- |
| 65 | +
|
| 66 | +<a href="/checkout">🛒 {cart?.length ?? 0} 点</a> |
| 67 | +``` |
| 68 | + |
| 69 | +### APIエンドポイント |
| 70 | + |
| 71 | +APIエンドポイントでは、セッションは`context`オブジェクト上で利用できます。たとえば、ショッピングカートに商品を追加する例です。 |
| 72 | + |
| 73 | +```ts title="src/pages/api/addToCart.ts" "context.session" |
| 74 | +export async function POST(context: APIContext) { |
| 75 | + const cart = await context.session?.get('cart') || []; |
| 76 | + const data = await context.request.json<{ item: string }>(); |
| 77 | + if (!data?.item) { |
| 78 | + return new Response('Item is required', { status: 400 }); |
| 79 | + } |
| 80 | + cart.push(data.item); |
| 81 | + await context.session?.set('cart', cart); |
| 82 | + return Response.json(cart); |
| 83 | +} |
| 84 | +``` |
| 85 | + |
| 86 | +### アクション |
| 87 | + |
| 88 | +アクション内でも、`context`オブジェクト上でセッションにアクセスできます。たとえば、ショッピングカートに商品を追加する例です。 |
| 89 | + |
| 90 | +```ts title="src/actions/addToCart.ts" "context.session" |
| 91 | +import { defineAction } from 'astro:actions'; |
| 92 | +import { z } from 'astro:schema'; |
| 93 | + |
| 94 | +export const server = { |
| 95 | + addToCart: defineAction({ |
| 96 | + input: z.object({ productId: z.string() }), |
| 97 | + handler: async (input, context) => { |
| 98 | + const cart = await context.session?.get('cart'); |
| 99 | + cart.push(input.productId); |
| 100 | + await context.session?.set('cart', cart); |
| 101 | + return cart; |
| 102 | + }, |
| 103 | + }), |
| 104 | +}; |
| 105 | +``` |
| 106 | + |
| 107 | +### ミドルウェア |
| 108 | + |
| 109 | +:::caution |
| 110 | +エッジミドルウェアでは、現在セッションはサポートされていません。 |
| 111 | +::: |
| 112 | + |
| 113 | +ミドルウェア内では、`context`オブジェクト上でセッションにアクセスできます。たとえば、セッションに最終訪問した時刻を保存する例です。 |
| 114 | + |
| 115 | +```ts title="src/middleware.ts" "context.session" |
| 116 | +import { defineMiddleware } from 'astro:middleware'; |
| 117 | + |
| 118 | +export const onRequest = defineMiddleware(async (context, next) => { |
| 119 | + context.session?.set('lastVisit', new Date()); |
| 120 | + return next(); |
| 121 | +}); |
| 122 | +``` |
| 123 | + |
| 124 | +## セッションデータの型 |
| 125 | + |
| 126 | +デフォルトではセッションデータに型はなく、任意のキーに好きなデータを保存できます。値のシリアライズやデシリアライズには、コンテンツコレクションやアクションでも使われている [devalue](https://github.com/Rich-Harris/devalue) が使用されます。そのため、文字列・数値・`Date`・`Map`・`Set`・`URL`・配列・プレーンオブジェクトなど、同じ型がサポートされています。 |
| 127 | + |
| 128 | +必要に応じて、`src/env.d.ts`ファイルを作成し、`App.SessionData`型を宣言することでセッションデータにTypeScriptの型を付けることもできます。 |
| 129 | + |
| 130 | +```ts title="src/env.d.ts" |
| 131 | +declare namespace App { |
| 132 | + interface SessionData { |
| 133 | + user: { |
| 134 | + id: string; |
| 135 | + name: string; |
| 136 | + }; |
| 137 | + cart: string[]; |
| 138 | + } |
| 139 | +} |
| 140 | +``` |
| 141 | + |
| 142 | +これにより、エディター上で型チェックと補完を受けながらセッションデータにアクセスできます。 |
| 143 | + |
| 144 | +```ts title="src/components/CartButton.astro" |
| 145 | +--- |
| 146 | +const cart = await Astro.session?.get('cart'); |
| 147 | +// const cart: string[] | undefined |
| 148 | + |
| 149 | +const something = await Astro.session?.get('something'); |
| 150 | +// const something: any |
| 151 | + |
| 152 | +Astro.session?.set('user', { id: 1, name: 'Houston' }); |
| 153 | +// Error: Argument of type '{ id: number; name: string }' is not assignable to parameter of type '{ id: string; name: string; }'. |
| 154 | +--- |
| 155 | +``` |
| 156 | + |
| 157 | +:::caution |
| 158 | +これは型チェック専用であり、実行時のセッション動作には影響しません。ユーザーのセッションに既にデータが保存されている状態で型を変更すると、実行時エラーが発生する可能性があるため注意してください。 |
| 159 | +::: |
0 commit comments