Auto Farm Creation With LINE OAuth: A Step-by-Step Guide
Hey guys! Today, we're diving into how to automatically create a farm for new users when they sign up using LINE OAuth. This is a fantastic way to streamline the user experience and get them engaged right from the start. We'll be focusing on a specific task: TASK-071-1, which outlines the implementation details. Let's get started!
Understanding the Task: Atomic Implementation of Single Farm Auto-Creation
Our main objective is to seamlessly create a default farm for new users authenticating via LINE OAuth. This means when someone signs up using their LINE account, a farm is automatically set up for them in the background. This entire process must feel invisible to the user, providing a smooth and intuitive experience. Think of it as planting the seeds for their digital farming journey right from the get-go! This automated process enhance user engagement and ensures that new users have a functional starting point within the application.
Key Deliverables
To achieve this, we'll be modifying the src/lib/auth.ts file to include the logic for automatic farm creation. This functionality will be triggered by better-auth hooks during the LINE OAuth callback process. The integration points will be:
- LINE OAuth Callback: The starting point of the authentication flow.
- Farm Creation: The core logic for setting up the default farm.
- Profile Page: Where the user lands after successful authentication and farm creation.
Manual Implementation Instructions
Since this task requires manual implementation, here’s what you, the awesome developer, need to do:
-
Create a Feature Branch: Start by branching from the
mainbranch:feature/task-071-1-single-farm-auto-creation -
Add better-auth Hook: Implement an
afterhook for the LINE OAuth callback using better-auth. -
Implement Farm Creation Logic: Add the necessary code to create a farm with default values.
-
Add Single Farm Validation: Implement validation to ensure each user has only one farm at the application level.
-
Validate: Run the following commands to ensure everything is working correctly:
npm run buildnpm run lintnpm test(Ensure 100% pass rate)
-
Commit and Create Pull Request: Commit your changes with a descriptive message and create a pull request.
Technical Requirements: The Building Blocks
Before we dive into the code, let's quickly run through the technologies we'll be using:
- Framework: Next.js 14 (App Router)
- Language: TypeScript (strict mode enabled)
- Database: PostgreSQL with Prisma ORM
- Authentication: better-auth v1.3.34 with LINE OAuth
- Testing: Built-in validation commands
Modifying src/lib/auth.ts
This is the file where the magic happens. We'll be adding the better-auth hooks to this file to trigger the farm creation process.
Exact Implementation Requirements: The Nitty-Gritty
Here's a detailed breakdown of what needs to be implemented:
- Import Required: Import
createAuthMiddlewarefrom "better-auth/api". - Hook Configuration: Add
hooks.afterarray to the better-auth config. - Matcher Function: Target LINE OAuth callback paths.
- Farm Creation Logic: Check for an existing farm; if none exists, create one with default values.
- Error Handling: Implement graceful failure handling to prevent authentication from breaking.
- Performance: Ensure the farm creation process adds no more than 200ms of latency.
Farm Creation Logic: The Heart of the Operation
Here’s the code snippet you'll need to add to your src/lib/auth.ts file within the betterAuth config:
hooks: {
after: [
{
matcher(context) {
return context.path === "/sign-up/social" ||
context.path === "/sign-in/social";
},
handler: createAuthMiddleware(async (ctx) => {
if (ctx.context.newSession && ctx.context.newSession.user) {
const userId = ctx.context.newSession.user.id;
// Check if user already has a farm
const existingFarm = await prisma.farm.findFirst({
where: { ownerId: userId }
});
if (!existingFarm) {
// Create default farm
await prisma.farm.create({
data: {
name: "ฟาร์มขà¸à¸‡à¸‰à¸±à¸™",
province: "ไม่ระบุ",
ownerId: userId,
}
});
}
}
})
}
]
}
This code checks if a user already has a farm. If not, it creates one with a default name (in Thai) and sets the province to "unspecified".
UI/UX Requirements: Keeping it Smooth and Friendly
- Seamless Experience: The farm creation process should be invisible to the user.
- Performance: Complete the farm creation before the profile page redirect (under 200ms).
- Mobile Optimization: Ensure compatibility with LINE WebView.
- Thai Language: Use Thai for the default farm name.
Acceptance Criteria: Ensuring Quality
Before you consider the task complete, make sure all these criteria are met:
- [ ]
npm run buildpasses with ZERO errors or warnings. - [ ]
npm run lintpasses with ZERO violations. - [ ]
npx tsc --noEmitpasses (TypeScript compilation). - [ ] New LINE OAuth users get a default farm created automatically.
- [ ] Existing users with farms are not affected.
- [ ] Farm creation completes before profile redirect.
- [ ] No authentication errors or timeouts.
Git Workflow: Staying Organized
-
Branch Name:
feature/task-071-1-single-farm-auto-creation -
Source Branch: MUST branch from the latest
main. -
No Merge Conflicts: The branch must be clean and mergeable.
-
Commit Format:
feat: implement single farm auto-creation with LINE OAuth hooks - Address TASK-071-1: Single Farm Auto-Creation - Add better-auth after hooks for LINE OAuth callback - Implement automatic farm[0] creation for new users - Build validation: 100% PASS (0 errors, 0 warnings) - Linter validation: 100% PASS (0 violations) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Validation Checklist: Double-Checking Your Work
Before you commit, run through this checklist:
- [ ]
npm run build→ Must show "✓ Compiled successfully" - [ ]
npm run lint→ Must show "✓ Lint complete" - [ ] Manual test in LINE WebView
- [ ] No console errors in the browser
- [ ] TypeScript compilation successful
Implementation Instructions: Step-by-Step
-
Create Feature Branch:
git checkout main git pull origin main git checkout -b feature/task-071-1-single-farm-auto-creation -
Implementation: Add better-auth hooks to
src/lib/auth.ts -
Validation:
npm run build # Must pass npm run lint # Must pass -
Commit Changes:
git add . git commit -m "feat: implement single farm auto-creation..." -
Push Branch:
git push -u origin feature/task-071-1-single-farm-auto-creation -
Create Pull Request: Use
/pr [feedback]after successful implementation
Related Context: Resources and Dependencies
- Context Issue: #71 (for reference only)
- No Task Dependencies: This task must be executable independently
- Reference Materials: better-auth hooks documentation, Issue #71 context
Conclusion: You've Got This!
And that's it, folks! By following these steps, you'll be able to automatically create farms for new users signing up with LINE OAuth. This enhances the user experience, increases engagement, and gets them hooked on your platform from the get-go. Remember to validate your work, follow the Git workflow, and most importantly, have fun! Good luck, and happy coding! This task has been assigned to mojisejr with the labels atomic, authentication, better-auth, independent-execution, and manual.