Unable to retrieve user email from clerk middleware

I have a table in supabase called Users which needs email and authId.I want to update these user data from the clerk. However, I am not able to retrieve the email address from the clerk’s middleware. I need help on how to get the email address.

I have tried to retrieve the email from UserId using getAuth by importing it from "@clerk/nextjs/client". But not successful.

import { clerkMiddleware } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { supabase } from "./utils/supabase/supabase";
import { getUser } from "@clerk/nextjs/client";

const isProtectedRoute = (req) => {
  const protectedPaths = ["/add-listing", "/(api|trpc)(.*)"];
  return protectedPaths.some((path) => req.url.includes(path));
};

export default clerkMiddleware(async (auth, req) => {
  console.log("Middleware is triggered");

  const { userId, sessionClaims } = auth() || {};

  console.log("userId:", userId);
  console.log("sessionClaims:", sessionClaims);

  if (userId) {
    console.log("User is authenticated:", userId);

    const user = await getAuth({ userId });
    const email = user.email;
    const authId = userId;

    console.log("Email:", email);
    console.log("authId:", authId);
    const { error } = await supabase.from("Users").upsert({ email, authId });

    if (error) {
      console.error("Error inserting user into Supabase:", error);
    } else {
      console.log("User inserted or updated in Supabase successfully");
    }
  } else {
    console.log("User is not authenticated");
  }

  if (isProtectedRoute(req) && !userId) {
    return new Response("Unauthorized", { status: 401 });
  }

  return NextResponse.next();
});

export const config = {
  matcher: [
    // Match API routes or specific protected paths
    "/add-listing",
    "/(api|trpc)(.*)",

    "/((?!_next|.*\.).*)",
  ]
};

  1. We import getAuth from “@clerk/nextjs/server” instead of the client version.
  2. We use await getAuth(req) to get the userId.
  3. To get the user’s email, we use req.auth.user which gives us access to the full user object.
  4. The email is accessed via user.emailAddresses[0].emailAddress. This assumes the user has at least one email address associated with their account.
import { clerkMiddleware, getAuth } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { supabase } from "./utils/supabase/supabase";

const isProtectedRoute = (req) => {
  const protectedPaths = ["/add-listing", "/(api|trpc)(.*)"];
  return protectedPaths.some((path) => req.url.includes(path));
};

export default clerkMiddleware(async (req, evt) => {
  console.log("Middleware is triggered");

  const { userId } = await getAuth(req);

  console.log("userId:", userId);

  if (userId) {
    console.log("User is authenticated:", userId);

    const user = await req.auth.user;
    const email = user.emailAddresses[0].emailAddress;
    const authId = userId;

    console.log("Email:", email);
    console.log("authId:", authId);

    const { error } = await supabase.from("Users").upsert({ email, authId });

    if (error) {
      console.error("Error inserting user into Supabase:", error);
    } else {
      console.log("User inserted or updated in Supabase successfully");
    }
  } else {
    console.log("User is not authenticated");
  }

  if (isProtectedRoute(req) && !userId) {
    return new Response("Unauthorized", { status: 401 });
  }

  return NextResponse.next();
});

export const config = {
  matcher: [
    "/add-listing",
    "/(api|trpc)(.*)",
    "/((?!_next|.*\.).*)",
  ],
};
New contributor

cihanolmalibu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Unable to retrieve user email from clerk middleware

I have a table in supabase called Users which needs email and authId.I want to update these user data from the clerk. However, I am not able to retrieve the email address from the clerk’s middleware. I need help on how to get the email address.

I have tried to retrieve the email from UserId using getAuth by importing it from "@clerk/nextjs/client". But not successful.

import { clerkMiddleware } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { supabase } from "./utils/supabase/supabase";
import { getUser } from "@clerk/nextjs/client";

const isProtectedRoute = (req) => {
  const protectedPaths = ["/add-listing", "/(api|trpc)(.*)"];
  return protectedPaths.some((path) => req.url.includes(path));
};

export default clerkMiddleware(async (auth, req) => {
  console.log("Middleware is triggered");

  const { userId, sessionClaims } = auth() || {};

  console.log("userId:", userId);
  console.log("sessionClaims:", sessionClaims);

  if (userId) {
    console.log("User is authenticated:", userId);

    const user = await getAuth({ userId });
    const email = user.email;
    const authId = userId;

    console.log("Email:", email);
    console.log("authId:", authId);
    const { error } = await supabase.from("Users").upsert({ email, authId });

    if (error) {
      console.error("Error inserting user into Supabase:", error);
    } else {
      console.log("User inserted or updated in Supabase successfully");
    }
  } else {
    console.log("User is not authenticated");
  }

  if (isProtectedRoute(req) && !userId) {
    return new Response("Unauthorized", { status: 401 });
  }

  return NextResponse.next();
});

export const config = {
  matcher: [
    // Match API routes or specific protected paths
    "/add-listing",
    "/(api|trpc)(.*)",

    "/((?!_next|.*\.).*)",
  ]
};

  1. We import getAuth from “@clerk/nextjs/server” instead of the client version.
  2. We use await getAuth(req) to get the userId.
  3. To get the user’s email, we use req.auth.user which gives us access to the full user object.
  4. The email is accessed via user.emailAddresses[0].emailAddress. This assumes the user has at least one email address associated with their account.
import { clerkMiddleware, getAuth } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { supabase } from "./utils/supabase/supabase";

const isProtectedRoute = (req) => {
  const protectedPaths = ["/add-listing", "/(api|trpc)(.*)"];
  return protectedPaths.some((path) => req.url.includes(path));
};

export default clerkMiddleware(async (req, evt) => {
  console.log("Middleware is triggered");

  const { userId } = await getAuth(req);

  console.log("userId:", userId);

  if (userId) {
    console.log("User is authenticated:", userId);

    const user = await req.auth.user;
    const email = user.emailAddresses[0].emailAddress;
    const authId = userId;

    console.log("Email:", email);
    console.log("authId:", authId);

    const { error } = await supabase.from("Users").upsert({ email, authId });

    if (error) {
      console.error("Error inserting user into Supabase:", error);
    } else {
      console.log("User inserted or updated in Supabase successfully");
    }
  } else {
    console.log("User is not authenticated");
  }

  if (isProtectedRoute(req) && !userId) {
    return new Response("Unauthorized", { status: 401 });
  }

  return NextResponse.next();
});

export const config = {
  matcher: [
    "/add-listing",
    "/(api|trpc)(.*)",
    "/((?!_next|.*\.).*)",
  ],
};
New contributor

cihanolmalibu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật