JS20

Documentation

JS20 - Documentation

Auth emails

Auth emails are used for verifying emails on signup and password reset. You can send emails by providing a sendEmail function in the Authenticator config.

/**
 * Configuration for authentication plugins
 * @param baseURL The base URL of your app, used for redirecting users after login
 * @param secret A secret key used for signing tokens or cookies
 * @param useEmailPassword Whether to enable email and password authentication, defaults to true
 * @param expiresIn The expiration time for tokens or sessions in milliseconds
 * @param cookie Configuration for authentication cookies
 */
export interface AuthConfig {
    baseURL?: string;
    secret?: string;
    useEmailPassword?: boolean;
    expiresIn?: number;
    cookie?: CookieConfig;
    sendEmail?: (email: AuthEmail) => Promise<void>;
}

/**
 * An email to send for authentication purposes
 * @param type The type of email to send (verification, reset, change), in case you want to customize the email content with your own subject or text
 * @param to The recipient's email address
 * @param url The URL to include in the email for the user to click
 * @param subject A simple default subject for the email
 * @param text A simple default text body for the email
 */
export interface AuthEmail {
    type: AuthEmailType;
    to: string;
    url: string;
    subject: string;
    text: string;
}

/**
 * Configuration for authentication cookies
 * @param domain The domain for which the cookie is valid, required in production
 * @param path The path for which the cookie is valid
 */
export interface CookieConfig {
    domain?: string;
    path?: string;
}

Here is an example of a simple sendEmail function using sendgrid:

import sgMail from '@sendgrid/mail';

sgMail.setApiKey(process.env.SENDGRID_API_KEY!);

const auth = new BetterAuth(database, {
    useEmailPassword: true,
    sendEmail: async (email: AuthEmail) => {
        const { to, url, subject, text } = email;

        const msg = {
            to,
            from: '[email protected]',
            subject,
            text,
            html: `
                <div>
                    <p>${text}</p>
                    ${url ? `
                        <a href="${url}">
                            Open Link
                        </a>` : ''}
                </div>
            `
        };

        await sgMail.send(msg);
    }
});
JS20