|
| 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' outputでは不要 |
| 21 | +const cart = await Astro.session?.get('cart'); |
| 22 | +--- |
| 23 | +
|
| 24 | +<a href="/checkout">🛒 {cart?.length ?? 0} items</a> |
| 25 | +``` |
| 26 | + |
| 27 | +## セッションの設定 |
| 28 | + |
| 29 | +セッションを使うには、セッションデータを保存するためのストレージドライバーが必要です。[Node](/ja/guides/integrations-guide/node/#セッション)、[Cloudflare](/ja/guides/integrations-guide/cloudflare/#sessions)、[Netlify](/ja/guides/integrations-guide/netlify/#セッション)のアダプターはデフォルトのドライバーを自動的に設定しますが、その他のアダプターでは現在[ドライバーを手動で指定](/ja/reference/configuration-reference/#sessiondriver)する必要があります。 |
| 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/#session-options)を参照してください。 |
| 42 | +</ReadMore> |
| 43 | + |
| 44 | + |
| 45 | +## セッションデータの操作 |
| 46 | + |
| 47 | +[`session`オブジェクト](/ja/reference/api-reference/#session)を使用すれば、保存されたユーザー状態の操作(例: ショッピングカートへのアイテム追加)やセッションIDの操作(例: ログアウト時のセッションIDクッキーの削除)が可能です。このオブジェクトは、Astroコンポーネントやページでは`Astro.session`から、APIエンドポイント、ミドルウェア、アクションでは`context.session`からアクセスできます。 |
| 48 | + |
| 49 | +セッションは初回使用時に自動的に生成され、[`session.regenerate()`](/ja/reference/api-reference/#regenerate)でいつでも再生成したり、[`session.destroy()`](/ja/reference/api-reference/#destroy)で破棄したりできます。 |
| 50 | + |
| 51 | +多くのユースケースでは、[`session.get()`](/ja/reference/api-reference/#get)と[`session.set()`](/ja/reference/api-reference/#set)のみで十分です。 |
| 52 | + |
| 53 | +<ReadMore> |
| 54 | +詳細については、[セッションAPIリファレンス](/ja/reference/api-reference/#session)を参照してください。 |
| 55 | +</ReadMore> |
| 56 | + |
| 57 | +### Astroコンポーネントとページ |
| 58 | + |
| 59 | +`.astro`コンポーネントやページでは、グローバルな`Astro`オブジェクトを通じてセッションオブジェクトにアクセスできます。たとえば、ショッピングカート内のアイテム数を表示するには次のようにします。 |
| 60 | + |
| 61 | +```astro title="src/components/CartButton.astro" "Astro.session" |
| 62 | +--- |
| 63 | +export const prerender = false; // 'server' outputでは不要 |
| 64 | +const cart = await Astro.session?.get('cart'); |
| 65 | +--- |
| 66 | +
|
| 67 | +<a href="/checkout">🛒 {cart?.length ?? 0} items</a> |
| 68 | +``` |
| 69 | + |
| 70 | +### APIエンドポイント |
| 71 | + |
| 72 | +APIエンドポイントでは、`context`オブジェクトからセッションオブジェクトにアクセスできます。たとえば、ショッピングカートにアイテムを追加するには次のようにします。 |
| 73 | + |
| 74 | +```ts title="src/pages/api/addToCart.ts" "context.session" |
| 75 | +export async function POST(context: APIContext) { |
| 76 | + const cart = await context.session?.get('cart') || []; |
| 77 | + const data = await context.request.json<{ item: string }>(); |
| 78 | + if(!data?.item) { |
| 79 | + return new Response('Item is required', { status: 400 }); |
| 80 | + } |
| 81 | + cart.push(data.item); |
| 82 | + await context.session?.set('cart', cart); |
| 83 | + return Response.json(cart); |
| 84 | +} |
| 85 | +``` |
| 86 | + |
| 87 | +### アクション |
| 88 | + |
| 89 | +アクションでは、`context`オブジェクトからセッションオブジェクトにアクセスできます。たとえば、ショッピングカートにアイテムを追加するには次のようにします。 |
| 90 | + |
| 91 | +```ts title="src/actions/addToCart.ts" "context.session" |
| 92 | +import { defineAction } from 'astro:actions'; |
| 93 | +import { z } from 'astro/zod'; |
| 94 | + |
| 95 | +export const server = { |
| 96 | + addToCart: defineAction({ |
| 97 | + input: z.object({ productId: z.string() }), |
| 98 | + handler: async (input, context) => { |
| 99 | + const cart = await context.session?.get('cart'); |
| 100 | + cart.push(input.productId); |
| 101 | + await context.session?.set('cart', cart); |
| 102 | + return cart; |
| 103 | + }, |
| 104 | + }), |
| 105 | +}; |
| 106 | +``` |
| 107 | + |
| 108 | +### ミドルウェア |
| 109 | + |
| 110 | +:::note |
| 111 | +エッジミドルウェアではセッションはサポートされていません。 |
| 112 | +::: |
| 113 | + |
| 114 | +ミドルウェアでは、`context`オブジェクトからセッションオブジェクトにアクセスできます。たとえば、セッションに最終訪問日時を設定するには次のようにします。 |
| 115 | + |
| 116 | +```ts title="src/middleware.ts" "context.session" |
| 117 | +import { defineMiddleware } from 'astro:middleware'; |
| 118 | + |
| 119 | +export const onRequest = defineMiddleware(async (context, next) => { |
| 120 | + context.session?.set('lastVisit', new Date()); |
| 121 | + return next(); |
| 122 | +}); |
| 123 | +``` |
| 124 | + |
| 125 | +## セッションデータの型 |
| 126 | + |
| 127 | +デフォルトではセッションデータには型がなく、任意のキーに任意のデータを保存できます。値は[devalue](https://github.com/Rich-Harris/devalue)を使用してシリアライズ・デシリアライズされます。これはコンテンツコレクションやアクションで使用されているのと同じライブラリです。そのため、サポートされる型も同じで、文字列、数値、`Date`、`Map`、`Set`、`URL`、配列、プレーンなオブジェクトが含まれます。 |
| 128 | + |
| 129 | +`src/env.d.ts`ファイルを作成し、`App.SessionData`型の宣言を追加することで、セッションデータの[TypeScript型を定義](/ja/guides/typescript/#extending-global-types)することもできます。 |
| 130 | + |
| 131 | +```ts title="src/env.d.ts" |
| 132 | +declare namespace App { |
| 133 | + interface SessionData { |
| 134 | + user: { |
| 135 | + id: string; |
| 136 | + name: string; |
| 137 | + }; |
| 138 | + cart: string[]; |
| 139 | + } |
| 140 | +} |
| 141 | +``` |
| 142 | + |
| 143 | +これにより、エディターで型チェックと自動補完を使ってセッションデータにアクセスできるようになります。 |
| 144 | + |
| 145 | +```ts title="src/components/CartButton.astro" |
| 146 | +--- |
| 147 | +const cart = await Astro.session?.get('cart'); |
| 148 | +// const cart: string[] | undefined |
| 149 | + |
| 150 | +const something = await Astro.session?.get('something'); |
| 151 | +// const something: any |
| 152 | + |
| 153 | +Astro.session?.set('user', { id: 1, name: 'Houston' }); |
| 154 | +// Error: Argument of type '{ id: number; name: string }' is not assignable to parameter of type '{ id: string; name: string; }'. |
| 155 | +--- |
| 156 | +``` |
| 157 | + |
| 158 | +:::caution |
| 159 | +これは型チェックにのみ使用され、セッションのランタイムの動作には影響しません。ユーザーがセッションにデータを保存した状態で型を変更すると、ランタイムエラーが発生する可能性があるため、十分に注意してください。 |
| 160 | +::: |
0 commit comments