Search code examples
node.jsstripe-paymentsserverlessvercel

Stripe webhook returning 308 error when calling Vercel serverless function


I've set up a webhook with Stripe, which calls a serverless function when it's triggered.

The function is intended to update an entry in my database when it's called, suggesting that a user has signed up for a premium account.

When I run this locally, the webhook works perfectly. It triggers the API, updates the user and processes the payment.

However, when it gets run on live, I continually get a 308 error saying:

Redirecting to my-app-url.com

Here's the code for my function:

import { buffer } from "micro"
import { createClient } from "@supabase/supabase-js";

require("dotenv").config();

const stripe = require("stripe")(process.env.STRIPE_LIVE_KEY)

const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET

const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
const supabaseAnonKey = process.env.REACT_APP_SUPABASE_ANON_KEY

const supabase = createClient(supabaseUrl, supabaseAnonKey)

module.exports = async (req, res) => {

   const signature = req.headers["stripe-signature"]
   const reqBuffer = await buffer(req)

   let event 

   try {
    event = stripe.webhooks.constructEvent(reqBuffer, signature, endpointSecret)
   } catch (err) {
    console.log(err)
    return res.status(400).send(`Webhook error: ${err.message}`)
   }

   if (event.type === "checkout.session.completed") {
    console.log("Checkout completed!")
    const userId = String(event.data.object.client_reference_id)

    console.log(userId)

    const { error } = await supabase.from('profiles').update({ premium: 'true' }).eq('id', userId) 
    
    if (error) {
      console.log(error)
    }
   }

   res.send({ received: true })
}

When I check my function logs, it just seems like it's not even firing / reaching my API at all - there's no logs.

Does anyone have any suggestions?


Solution

  • The problem is the default domain redirect in Vercel.

    The recommended way is to redirect to www, so this is the format you should use:

    Wrong: https://[YOUR_DOMAIN].com/api/endpoint

    Right: https://www.[YOUR_DOMAIN].com/api/endpoint

    Cheers