feat: support auto subscribe to newsletter after sign up

This commit is contained in:
javayhu 2025-04-14 01:25:22 +08:00
parent 3ff522cff2
commit 9c5e7db748
3 changed files with 27 additions and 1 deletions

View File

@ -40,6 +40,7 @@ export const websiteConfig: WebsiteConfig = {
},
newsletter: {
provider: 'resend',
autoSubscribeAfterSignUp: false,
},
storage: {
provider: 's3',

View File

@ -6,9 +6,11 @@ import { sendEmail } from '@/mail';
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { admin } from 'better-auth/plugins';
import { subscribe } from '@/newsletter';
import { parse as parseCookies } from 'cookie';
import { Locale } from 'next-intl';
import { getUrlWithLocaleInCallbackUrl } from './urls/urls';
import { websiteConfig } from '@/config/website';
/**
* https://www.better-auth.com/docs/reference/options
@ -109,6 +111,28 @@ export const auth = betterAuth({
enabled: true,
},
},
databaseHooks: {
// https://www.better-auth.com/docs/concepts/database#database-hooks
user: {
create: {
after: async (user) => {
// Auto subscribe user to newsletter after sign up if enabled in website config
if (user.email && websiteConfig.newsletter.autoSubscribeAfterSignUp) {
try {
const subscribed = await subscribe(user.email);
if (!subscribed) {
console.error(`Failed to subscribe user ${user.email} to newsletter`);
} else {
console.log(`User ${user.email} subscribed to newsletter`);
}
} catch (error) {
console.error('Newsletter subscription error:', error);
}
}
},
},
},
},
plugins: [
// https://www.better-auth.com/docs/plugins/admin
// support user management, ban/unban user, manage user roles, etc.

View File

@ -67,7 +67,8 @@ export interface MailConfig {
* Newsletter configuration
*/
export interface NewsletterConfig {
provider: 'resend'; // The newsletter provider, only resend is supported for now
provider: 'resend'; // The newsletter provider, only resend is supported for now
autoSubscribeAfterSignUp?: boolean; // Whether to automatically subscribe users to the newsletter after sign up
}
/**