Home
back

Tanstack Start , full-stack 事例

id: 183, 2025-05-21

### 音声概要

・AIで生成された 音声概要になります。


ログイン認証 , Tanstack Start + D1 database

  • ログイン認証などのメモになります。
  • D1 に、ユーザーデータを保存

### 構成

  • Tanstack Start
  • D1
  • CF-workers

### 関連


### D1 + workers 連携 認証、書いたコード


  • Login
  • workers_auth/app/routes/login.tsx

https://github.com/kuc-arc-f/tanstack_start_3ex/blob/main/workers_auth/app/routes/login.tsx


  • signup
  • workers_auth/app/routes/signup.tsx

https://github.com/kuc-arc-f/tanstack_start_3ex/blob/main/workers_auth/app/routes/signup.tsx


  • 関連のファイル
  • __root.tsx : 認証データの読込
  • workers_auth/app/routes/__root.tsx
const fetchUser = createServerFn({ method: "GET" }).handler(async () => {
  const session = await useAppSession()
  if (!session.data.userEmail) {
    return null
  }

  return {
    email: session.data.userEmail,
  }
})

  • _authed.tsx : 認証データの判定
  • workers_auth/app/routes/_authed.tsx
  • createFileRoute, throw redirect に変更しました。
  • throw 部分、コメントに修正

import { createFileRoute, redirect } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/start"
import { Login } from "~/components/Login"
import { useAppSession } from "~/utils/session"

export const loginFn = createServerFn()
  .validator((d) => d as { email: string; password: string })
  .handler(async ({ data }) => {
    console.log("#loginFn");
    console.log(data);
    const user = {email: data.email}

    // Create a session
    const session = await useAppSession()

    await session.update({
      userEmail: user.email,
    })
  })

export const Route = createFileRoute("/_authed")({
  beforeLoad: ({ context }) => {
    console.log("#_authed.beforeLoad");
    console.log(context);
    if (!context.user) {
      //throw new Error("Not authenticated")
      throw redirect({
        to: "/login",
      });
    }
  },
  errorComponent: ({ error }) => {
    if (error.message === "Not authenticated") {
      return <Login />
    }

    throw error
  },
})

タスク管理 , Tanstack Start

  • タスク管理 の作成メモになります。
  • D1 に、データを保存
  • CF-workers + D1に連携します。

### 構成

  • Tanstack Start
  • D1
  • workers
  • React 19
  • vinxi
  • vite
  • zod
  • tailwindcss

### 書いたコード


  • dev-start
npm run dev

  • .env
  • API_URL , API_KEY 設定
VITE_API_URL=https://localhost
VITE_API_KEY="123"
VITE_USER_USERNAME="u1@example.com"
VITE_USER_PASSWORD="1234"