supabase: Enabling Supabase Auth Hook for send-email locally causes a 500 during call to supabase.auth.signUp

Decided to go ahead and turn this into an issue, since the documentation on leveraging the auth hook to work with resend doesn’t mention anything about local development, and the documentation on the auth hook suggests it can be enabled locally without any other information about other configurations that might need to be updated, so even if this isn’t an actual bug, I think clarifying any limitations I’m missing in the documentation would be a good improvement.

Let me know if there’s any other information I could provide to help triage this!

Discussed in https://github.com/orgs/supabase/discussions/29242

<div type='discussions-op-text'>

Originally posted by gmichopoulos September 11, 2024 Hi! I’ve been trying to configure my codebase to support local development of an end-to-end user signup flow including email confirmation through a resend email as described in the Supabase documentation here and here.

I finally got a test working that confirms that my new hook is successfully sending the desired email to resend, but I’m having trouble getting my call to supabase.auth.signUp to work upstream of the hook now. I previously had the following auth settings in my config.toml:

[auth]
enabled = true
# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used
# in emails.
site_url = "http://localhost:3000"
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
additional_redirect_urls = ["https://127.0.0.1:3000", "http://localhost:3000", "https://localhost:3000"]
# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
jwt_expiry = 3600
# If disabled, the refresh token will never expire.
enable_refresh_token_rotation = true
# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds.
# Requires enable_refresh_token_rotation = true.
refresh_token_reuse_interval = 10
# Allow/disallow new user signups to your project.
enable_signup = true
# Allow/disallow anonymous sign-ins to your project.
enable_anonymous_sign_ins = false
# Allow/disallow testing manual linking of accounts
enable_manual_linking = false

[auth.email]
# Allow/disallow new user signups via email to your project.
enable_signup = true
# If enabled, a user will be required to confirm any email change on both the old, and new email
# addresses. If disabled, only the new email is required to confirm.
double_confirm_changes = true
# If enabled, users need to confirm their email address before signing in.
enable_confirmations = true
# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email.
max_frequency = "1s"

[auth.email.template.confirmation]
subject = "Confirm Your Signup"
content_path = "./supabase/templates/confirm.html"

And was able to get through signup end to end using the template at that path, but now that I have commented that template override and updated my config to the following:

# [auth.email.template.confirmation]
# subject = "Confirm Your Signup"
# content_path = "./supabase/templates/confirm.html"

[auth.hook.send_email]
enabled = true
uri = "http://host.docker.internal:54321/functions/v1/send_email"
# Comma separated list of secrets
secrets = "env(SEND_EMAIL_HOOK_SECRET)"

I’m expecting to have signup trigger my function/hook but instead it’s raising the following error:

AuthApiError: Error sending confirmation mail
    at handleError (webpack-internal:///(action-browser)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:80:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async _handleRequest (webpack-internal:///(action-browser)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:123:9)
    at async _request (webpack-internal:///(action-browser)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:105:18)
    at async SupabaseAuthClient.signUp (webpack-internal:///(action-browser)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:280:23)
    at async signUp (webpack-internal:///(action-browser)/./actions/auth/signUp.ts:34:23)
    at async /Users/gmichopoulos/pt-studio/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:39:418
    at async rS (/Users/gmichopoulos/pt-studio/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:38:7978)
    at async r2 (/Users/gmichopoulos/pt-studio/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:41:1251)
    at async doRender (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/base-server.js:1438:30)
    at async cacheEntry.responseCache.get.routeKind (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/base-server.js:1599:28)
    at async DevServer.renderToResponseWithComponentsImpl (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/base-server.js:1507:28)
    at async DevServer.renderPageComponent (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/base-server.js:1924:24)
    at async DevServer.renderToResponseImpl (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/base-server.js:1962:32)
    at async DevServer.pipeImpl (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/base-server.js:920:25)
    at async NextNodeServer.handleCatchallRenderRequest (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/next-server.js:272:17)
    at async DevServer.handleRequestImpl (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/base-server.js:816:17)
    at async /Users/gmichopoulos/pt-studio/node_modules/next/dist/server/dev/next-dev-server.js:339:20
    at async Span.traceAsyncFn (/Users/gmichopoulos/pt-studio/node_modules/next/dist/trace/trace.js:154:20)
    at async DevServer.handleRequest (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/dev/next-dev-server.js:336:24)
    at async invokeRender (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/lib/router-server.js:174:21)
    at async handleRequest (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/lib/router-server.js:353:24)
    at async requestHandlerImpl (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/lib/router-server.js:377:13)
    at async Server.requestListener (/Users/gmichopoulos/pt-studio/node_modules/next/dist/server/lib/start-server.js:141:13) {
  __isAuthError: true,
  status: 500,
  code: 'unexpected_failure'
}
</div>

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 21 (1 by maintainers)

Most upvoted comments

I’m also experiencing this issue, I want to add that I can communicate directly with the edge function with: uri = "http://127.0.0.1:54321/functions/v1/send-email-resend"

The edge functions also work, but when a user signs up there’s no request being sent to the hook at the edge function. There’s nothing in the logs.

In Supabase studio I get the following error:

{
  "auth_event": {
    "action": "user_confirmation_requested",
    "actor_id": "620d49a0-b322-4d93-923c-a62b693f0d71",
    "actor_username": "ricardo@example.com",
    "actor_via_sso": false,
    "log_type": "user",
    "traits": {
      "provider": "email"
    }
  },
  "component": "api",
  "error": "500: Error running hook URI: http://127.0.0.1:54321/functions/v1/send-email-resend",
  "level": "error",
  "method": "POST",
  "msg": "500: Error sending confirmation email",
  "path": "/signup",
  "referer": "http://localhost:3000",
  "remote_addr": "192.168.65.1",
  "request_id": "fdc72a67-5ee3-4994-b216-6e0a893567f9",
  "time": "2024-09-16T07:41:22Z"
}

same auth.signUp doesnt work with NextJS , timeout error & error AuthRetryableFetchError: {}

@SimRunBot, signUp with NextJS used to work until very recently. I’ve created a bug report: https://github.com/supabase/supabase/issues/29294

same auth.signUp doesnt work with NextJS , timeout error & error AuthRetryableFetchError: {}

I didn’t find any solution but to avoid using supabase edge functions for this.

@ricardomatias 👇

My Work Around

For those encountering WebhookVerificationError with the error being Missing required headers when working with Supabase, here is the work around I’m using:

  • Keep in mind that I’m assuming this error only occurs when working locally.
  1. Add an environment variable to your .env* file to keep track of the running environment. Inspired by NODE, I’ve added this variable to my file DENO_ENV=development.
  2. Add this function to your codebase:
/**
 * Signs the webhook headers. Why? Because for some reason Supabase doesn't
 * sign the webhook headers when running locally... 🤷‍♂️
 *
 * USE THIS ONLY FOR LOCAL DEVELOPMENT!
 *
 * @param webhook The Webhook instance.
 * @param headers The request headers.
 * @param payload The request payload.
 * @returns The signed headers.
 */
function signWebhookHeader(webhook: Webhook, headers: {
  [k: string]: string;
}, payload: string): {
  [k: string]: string;
} {
  const whId = headers["webhook-id"];
  const whTimestamp = headers["webhook-timestamp"];

  const date = new Date(Number(whTimestamp) * 1000);

  const signature = webhook.sign(whId, date, payload);

  headers["webhook-signature"] = signature;
  return headers;
}
  1. Use the function above to sign the webhook header only when the running environment is meant for development:
Deno.serve(async (req: Request): Promise<Response> => {
  if (req.method !== "POST") {
    return new Response("not allowed", { status: 400 });
  }

  const payload = await req.text();
  let headers = Object.fromEntries(req.headers);
  const wh = new Webhook(hookSecret.replace("v1,whsec_", ""));

  const runningEnv = Deno.env.get("DENO_ENV");
  if (runningEnv === "development") {
    headers = signWebhookHeader(wh, headers, payload);
  }

  // your logic 👇

}

Code Example with Resend (using a React Email template):

send-email/index.ts

// Follow this setup guide to integrate the Deno language server with your editor:
// https://deno.land/manual/getting_started/setup_your_environment
// This enables autocomplete, go to definition, etc.

// Setup type definitions for built-in Supabase Runtime APIs
import "jsr:@supabase/functions-js/edge-runtime.d.ts";

import { render } from "npm:@react-email/components@0.0.26-canary.3";
import React from "npm:react@18.3.1";
import { Webhook } from "https://esm.sh/standardwebhooks@1.0.0";

import { resendClient } from "../_shared/clients.ts";
import { ConfirmEmail } from "./_templates/sign-up/confirm-email.tsx";

const resend = resendClient();
const hookSecret = Deno.env.get("SUPA_SEND_EMAIL_HOOK_SECRET") as string;

/**
 * Signs the webhook headers. Why? Because for some reason Supabase doesn't
 * sign the webhook headers when running locally... 🤷‍♂️
 *
 * USE THIS ONLY FOR LOCAL DEVELOPMENT!
 *
 * @param webhook The Webhook instance.
 * @param headers The request headers.
 * @param payload The request payload.
 * @returns The signed headers.
 */
function signWebhookHeader(webhook: Webhook, headers: {
  [k: string]: string;
}, payload: string): {
  [k: string]: string;
} {
  const whId = headers["webhook-id"];
  const whTimestamp = headers["webhook-timestamp"];

  const date = new Date(Number(whTimestamp) * 1000);

  const signature = webhook.sign(whId, date, payload);

  headers["webhook-signature"] = signature;
  return headers;
}

Deno.serve(async (req: Request): Promise<Response> => {
  if (req.method !== "POST") {
    return new Response("not allowed", { status: 400 });
  }

  const payload = await req.text();
  let headers = Object.fromEntries(req.headers);
  const wh = new Webhook(hookSecret.replace("v1,whsec_", ""));

  const runningEnv = Deno.env.get("DENO_ENV");
  if (runningEnv === "development") {
    headers = signWebhookHeader(wh, headers, payload);
  }

  try {
    const {
      user,
      email_data: { token, email_action_type },
    } = wh.verify(payload, headers) as {
      user: {
        email: string;
      };
      email_data: {
        token: string;
        token_hash: string;
        redirect_to: string;
        email_action_type: string;
        site_url: string;
        token_new: string;
        token_hash_new: string;
      };
    };

    let html: string;

    if (email_action_type === "signup") {
      html = await render(React.createElement(ConfirmEmail, { token: token }));
    } else {
      throw new Error("email_action_type not supported yet");
    }

    const { error } = await resend.emails.send({
      from: Deno.env.get("RESEND_FROM_EMAIL") ?? "",
      to: [user.email],
      subject: "Confirm your email address",
      html,
    });

    if (error) {
      throw error;
    }
  } catch (error) {
    console.log(error);
    return new Response(
      JSON.stringify({
        error: {
          http_code: error.code,
          message: error.message,
        },
      }),
      {
        status: 401,
        headers: { "Content-Type": "application/json" },
      },
    );
  }

  const responseHeaders = new Headers();
  responseHeaders.set("Content-Type", "application/json");
  return new Response(JSON.stringify({}), {
    status: 200,
    headers: responseHeaders,
  });
});

/* To invoke locally:

  1. Run `supabase start` (see: https://supabase.com/docs/reference/cli/supabase-start)
  2. Make an HTTP request:

  curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/send-email' \
    --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0' \
    --header 'Content-Type: application/json' \
    --data '{"name":"Functions"}'

*/

@gmichopoulos I’ve managed to get confirmation emails. It’s easier to check for errors by stopping the “supabase_edge_runtime_database” container and running supabase functions serve --no-verify-jwt --debug (from your terminal inside supabase’s folder).

The http://host.docker.internal:54321 proxy must be used in the config.toml or the container cannot reach the network.

config.toml

[auth.hook.send_email]
enabled = true
uri = "http://host.docker.internal:54321/functions/v1/send-email"
secret = "env(SEND_EMAIL_SECRET)"

In the end, my issues stemmed first from the dependencies of my function and later from an invalid webhook verification due to a missing “webhook-signature” header. I could solve the dependencies issues, but not the missing webhook-signature (which should have the secret).

Regarding the dependencies, my issues with them went away when I fetched all of them from “npm”. Before I was using “https://esm.sh” and some dependencies could not resolve. If you must use it, try adding “?bundle” at the end of the package name.

Example of my import-map.json (under supabase/functions)

{
    "imports": {
        "react": "npm:react@18.3.1",
        "@react-email/components": "npm:@react-email/components@0.0.25",
        "standardwebhooks": "npm:standardwebhooks@1.0.0",
        "resend": "npm:resend@4.0.0"
    }
}