User Data and Profiles
Managing user data and profiles is an important aspect of any application with authentication. This guide covers how to work with user data in Svelte Guardian, including creating and updating user profiles.
User Data Structure
Svelte Guardian stores core user data in the User
table/collection with the following standard fields:
id
: Unique identifieremail
: User’s email addressemailVerified
: Timestamp when email was verifiedname
: User’s display name (optional)image
: URL to user’s avatar image (optional)password
: Hashed password (for credentials provider)role
: User role for authorization
Extending the User Model
Using Prisma
When using Prisma, extend the User model in schema.prisma
:
After modifying your schema, run a migration:
Using MongoDB
With MongoDB, the schema is more flexible:
Accessing User Data
Server-Side Access
Access user data in server code:
Client-Side Access
Use the data in client components:
Your Profile
{user.name || user.email}
{user.role}Personal Information
Email: {user.email}
First Name: {user.firstName || 'Not set'}
Last Name: {user.lastName || 'Not set'}
Phone: {user.phoneNumber || 'Not set'}
Birth Date: {user.birthDate ? new Date(user.birthDate).toLocaleDateString() : 'Not set'}
Address
{user.address.street}
{user.address.city}, {user.address.state || ''} {user.address.zipCode}
{user.address.country}
Please sign in to view your profile.
{/if}Profile Editing
Create a profile editing form:
Edit Profile
{#if form?.error}And create the server action to handle profile updates:
Avatar/Profile Image Management
Add functionality for users to upload profile images:
Update Profile Picture
{#if form?.error}Handle the image upload server-side:
Changing Password
Create a password change form:
Change Password
{#if form?.error}And the server handler:
Best Practices
- Data Validation: Always validate user input on both client and server
- Security: Never expose sensitive information like hashed passwords
- Incremental Loading: For complex profiles, load data incrementally
- Atomic Updates: Update specific parts of the profile independently
- Error Handling: Provide clear feedback when updates fail
- Data Privacy: Allow users to download or delete their data
- Image Optimization: Resize and compress profile images
- Performance: Use database indexes for efficient user lookup
Next Steps
After implementing user profiles, consider these enhancements: