Your Deno server code using Supabase looks generally well-structured and should work for generating invitation codes or creating email invitations while properly handling CORS and authorization. Here are some suggestions and clarifications to improve robustness, security, and maintainability:
1. Validation of Input
Currently, you extract method and email from the request body without validating their types. It's good practice to validate incoming data (for example, ensure method is a string and email is a valid email if present).
You could add a simple check like:
ts
if (typeof method !== "string" || (method === "email" && (typeof email !== "string" || !validateEmail(email)))) {
return new Response(JSON.stringify({ error: "Invalid method or email format" }), { status: 400, headers: {...} });
}
// Simple regex email validation
function validateEmail(email: string) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
2. Better Extraction of school_id
You call a stored procedure get_user_school_id and destructure it directly into schoolId, but Supabase .rpc() methods return { data, error }, where data may be an object or array depending on the RPC definition.
Otherwise, your current code may have schoolId as an object or array instead of the expected scalar value.
3. Authorization Header Usage
You're passing the full Authorization header from the inbound client directly to the Supabase client. Commonly, the header contains . Supabase SDK expects only the token:
Certainly! Here is the full updated script incorporating all the improvements:
ts
User
error: when generating code: Edge Function returned a non-2xx status code
Assistant
The error message "Edge Function returned a non-2xx status code" means the function you deployed is returning a response with status code outside the 200–299 range. This typically indicates the function encountered an error before successfully completing the request.
For your code, possible reasons for this error are:
1. Authorization failure
Your function relies on the Authorization header containing a valid JWT token for Supabase. If the token is missing, invalid, or expired, your function responds with a 401 Unauthorized.
Check in your client request:
Are you passing the Authorization: Bearer <token> header correctly?
Is the token valid and still active?
If the token is not set or invalid, your function returns:
json
{ "error": "Unauthorized - missing token" }
or
json
{ "error": "Unauthorized" }
2. RPC call failure (get_user_school_id)
If your RPC (stored procedure) get_user_school_id fails or returns unexpected data, your function returns 400 with:
json
{ "error": "Could not determine school ID" }
Double-check:
The RPC exists in your Supabase database.
It returns an object or array with .school_id key, or adapt the extraction logic accordingly.
The user calling the RPC has permission to run it.
You can add extra logs or temporarily return the raw RPC response to debug.
3. Inserting invitation fails
If inserting into student_invites failed (e.g., DB constraints, missing columns, or permissions), you return 500 with error details:
json
{ "error": "Failed to create invitation", "details": "some message" }
Check:
Table student_invites exists with columns exactly matching what you insert.
Your service role or anon key has insert permission on the table.
The status column accepts "pending" as a valid value.
User
Edge Function returned a non-2xx status code
Assistant
The generic error "Edge Function returned a non-2xx status code" just means your function returned some 4xx or 5xx response, indicating failure.
To help you debug this effectively, here are actionable steps to pinpoint the cause and fix it:
1. Enable detailed console logging in your Edge Function
Add these at key points to directly log request info and failures:
ts
User
import React, { useState, useEffect } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { supabase } from "@/integrations/supabase/client";
import Navbar from "@/components/layout/Navbar";
import Footer from "@/components/landing/Footer";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { toast } from "sonner";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Mail, User, ArrowLeft, Copy, UserPlus, RefreshCw } from "lucide-react";
import { useNavigate } from "react-router-dom";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { getCurrentUserSchoolId } from "@/utils/schoolUtils";
// Define the schema for student invite form
const addStudentSchema = z.object({
email: z.string().email({ message: "Please enter a valid email address" }).optional(),
method: z.enum(["invite", "code"], {
required_error: "Please select a method",
}),
});
Thanks for sharing your React frontend code! It looks pretty solid overall. Here are a few notes and suggestions focusing on your interaction with the invite-student edge function and general best practices:
Adjust this logic based on your actual RPC output.
3. Validate input from client
Add validation to input, e.g., check that method is "code" or "email" and if email invitation, that email is a valid email string. This prevents bad requests or injection.
4. Use .select() on insert only if you want the returned rows
You use .select() after inserts. This is valid if you want the inserted row back, but if you don’t need them, avoid .select() to reduce response overhead:
if (inviteError) {
console.error("Insert error:", inviteError);
}
Common quick fixes:
Ensure the client sends Authorization: Bearer <token> header.
Confirm environment variables SUPABASE_URL and SUPABASE_ANON_KEY are correctly set in the edge function environment.
Validate that your stored procedure get_user_school_id returns a field called school_id. If it returns a scalar (e.g., just a number), then change extraction logic from:
If after these steps the problem remains unclear, please share the error logs printed on server or returned error message from your Edge Function (body + status), so I can help diagnose more precisely.
Make sure both SUPABASE_URL and SUPABASE_ANON_KEY are correctly set in your deployment environment (Edge function environment variables).
Confirm they exactly match your Supabase project values.
3. Validate your get_user_school_id RPC
Test your RPC in Supabase SQL editor or PostgREST directly to verify it returns { school_id: <number> } or an array like [ { school_id: <number> } ] for the authenticated user.
Adjust code that extracts schoolId accordingly.
4. Test Authorization header on the client
When you call your Edge function, ensure your fetch/client passes auth as:
Without a valid Authorization header, the function returns 401.
5. Add a fallback to log raw RPC and insert errors
If the RPC or insert to student_invites fails, log and return the full error message for debugging:
ts
if (schoolIdError) {
console.error("RPC error:", schoolIdError);
}
...
if (inviteError) {
console.error("Insert error:", inviteError);
}
Summary
Enable full logging in your Edge function and check your function's logs after execution/deployment.
Verify RPC output matches what you expect.
Ensure proper auth token is sent by your client in Authorization header.
Confirm environment variables are properly configured for your edge environment.
If you want, send me the logs or full error body you get from the Edge function after these logging additions. I can then help pinpoint the exact step that’s failing.
const fetchInvites = async () => {
if (!schoolId) {
console.log("No school ID available, cannot fetch invites");
return;
}
try {
console.log("Fetching invites for school ID:", schoolId);
// Try to fetch from student_invites table
const { data: studentInvites, error: studentInviteError } = await supabase
.from("student_invites")
.select("*")
.eq("school_id", schoolId)
.order("created_at", { ascending: false })
.limit(10);
// Only update state if component is still mounted
if (isMounted) {
if (studentInvites && studentInvites.length > 0) {
console.log("Found student invites:", studentInvites);
setInvites(studentInvites as StudentInvite[]);
return;
} else {
console.log("No student invites found or error:", studentInviteError);
}
// Fallback to teacher_invitations table for display
const { data, error } = await supabase
.from("teacher_invitations")
.select("*")
.eq("school_id", schoolId)
.order("created_at", { ascending: false })
.limit(10);
if (error) {
console.error("Error fetching teacher invitations:", error);
throw error;
}
// Convert teacher_invitations to our StudentInvite type
const studentInviteData: StudentInvite[] = (data || []).map(invite => ({
id: invite.id,
email: invite.email,
code: null,
created_at: invite.created_at,
expires_at: invite.expires_at,
status: invite.status
}));
console.log("Using teacher invitations as fallback:", studentInviteData);
setInvites(studentInviteData);
}
} catch (error: any) {
if (isMounted) {
console.error("Error fetching student invites:", error);
toast.error("Failed to load student invites");
}
}
};
// Only fetch if we have a schoolId
if (schoolId) {
fetchInvites();
}
// Cleanup function to prevent state updates after unmount
return () => {
isMounted = false;
};
}, [schoolId, refreshTrigger]);
const onSubmit = async (values: AddStudentFormValues) => {
if (!user || !schoolId) {
toast.error("You must be logged in with a school account to invite students");
return;
}
code
setIsLoading(true);
try {
if (values.method === "invite" && values.email) {
console.log("Creating email invitation for:", values.email);
// Call our invite-student edge function with proper headers
const { data, error } = await supabase.functions.invoke("invite-student", {
body: {
method: "email",
email: values.email
}
});
if (error) {
console.error("Error from invite-student function:", error);
throw error;
}
console.log("Invitation created:", data);
toast.success(`Invitation sent to ${values.email}`);
form.reset();
}
// Refresh the invites list
setRefreshTrigger(prev => prev + 1);
} catch (error: any) {
console.error("Error inviting student:", error);
toast.error(error.message || "Failed to invite student");
} finally {
setIsLoading(false);
}
};
const copyInviteCode = () => {
if (!generatedCode) {
toast.error("No code available to copy");
return;
}
code
navigator.clipboard.writeText(generatedCode);
toast.success("Code copied to clipboard!");
try {
console.log("Calling invite-student edge function with method: code");
// Get the auth token for the request
const { data: { session } } = await supabase.auth.getSession();
if (!session) {
throw new Error("No active session found");
}
// Use invite-student function with proper headers
const { data, error } = await supabase.functions.invoke("invite-student", {
body: { method: "code" }
});
if (error) {
console.error("Error from invite-student function:", error);
throw new Error(error.message || "Failed to generate invitation code");
}
if (!data) {
throw new Error("No data returned from the server");
}
console.log("Generated invite code response:", data);
if (!data.code) {
console.error("Invalid response format:", data);
throw new Error("Code not found in server response");
}
setGeneratedCode(data.code);
toast.success("Student invitation code generated");
// Refresh the invites list
setRefreshTrigger(prev => prev + 1);
} catch (error: any) {
console.error("Error generating invite code:", error);
toast.error(error.message || "Failed to generate invitation code");
} finally {
setIsGeneratingCode(false);
}
};
return (
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={() => navigate('/admin')}
>
Back to Admin
Student Management
However if you are using supabase-js version 2+ functions.invoke, it should parse this for you. Just keep in mind that the API can differ — check your installed supabase-js version docs.
5. Optional: Disabling buttons during processing
You already disable buttons during loading. Nice! Just be sure all paths set the loading state accordingly.
You may want to check if the user has a valid session early on and redirect to login if not.
To improve user experience, consider adding pagination or infinite scroll for invite lists.
If you want, I can help generate a fully updated React component with these fixes applied. Just let me know!
import React, { useState, useEffect } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { supabase } from "@/integrations/supabase/client";
import Navbar from "@/components/layout/Navbar";
import Footer from "@/components/landing/Footer";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { toast } from "sonner";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import {
Mail,
ArrowLeft,
Copy,
UserPlus,
RefreshCw,
} from "lucide-react";
import { useNavigate } from "react-router-dom";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
// Define the schema for student invite form with "email" method (not "invite")
const addStudentSchema = z.object({
email: z.string().email({ message: "Please enter a valid email address" }).optional(),
method: z.enum(["email", "code"], {
required_error: "Please select a method",
}),
});
type AddStudentFormValues = z.infer<typeof addStudentSchema>;
type StudentInvite = {
id: string;
email: string | null;
code: string | null;
created_at: string;
expires_at: string;
status: string;
};
const AdminStudents = () => {
const { user, profile, schoolId: authSchoolId } = useAuth();
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(false);
const [invites, setInvites] = useState<StudentInvite[]>([]);
const [generatedCode, setGeneratedCode] = useState("");
const [refreshTrigger, setRefreshTrigger] = useState(0);
const [isGeneratingCode, setIsGeneratingCode] = useState(false);
// Get the schoolId properly
const userProfileId = user?.id || null;
const schoolId = authSchoolId || profile?.organization?.id || null;
console.log("AdminStudents: Using user ID:", userProfileId);
console.log("AdminStudents: Using school ID:", schoolId);
const form = useForm<AddStudentFormValues>({
resolver: zodResolver(addStudentSchema),
defaultValues: {
email: "",
method: "code",
},
});
const selectedMethod = form.watch("method");
// Load student invites
useEffect(() => {
let isMounted = true;
const fetchInvites = async () => {
if (!schoolId) {
console.log("No school ID available, cannot fetch invites");
return;
}
try {
console.log("Fetching invites for school ID:", schoolId);
// Try to fetch from student_invites table
const { data: studentInvites, error: studentInviteError } = await supabase
.from("student_invites")
.select("*")
.eq("school_id", schoolId)
.order("created_at", { ascending: false })
.limit(10);
if (isMounted) {
if (studentInvites && studentInvites.length > 0) {
console.log("Found student invites:", studentInvites);
setInvites(studentInvites as StudentInvite[]);
return;
} else {
console.log("No student invites found or error:", studentInviteError);
}
// Fallback to teacher_invitations table for display
const { data, error } = await supabase
.from("teacher_invitations")
.select("*")
.eq("school_id", schoolId)
.order("created_at", { ascending: false })
.limit(10);
if (error) {
console.error("Error fetching teacher invitations:", error);
throw error;
}
const studentInviteData: StudentInvite[] = (data || []).map((invite) => ({
id: invite.id,
email: invite.email,
code: null,
created_at: invite.created_at,
expires_at: invite.expires_at,
status: invite.status,
}));
console.log("Using teacher invitations as fallback:", studentInviteData);
setInvites(studentInviteData);
}
} catch (error: any) {
if (isMounted) {
console.error("Error fetching student invites:", error);
toast.error("Failed to load student invites");
}
}
};
if (schoolId) {
fetchInvites();
}
return () => {
isMounted = false;
};
}, [schoolId, refreshTrigger]);
const onSubmit = async (values: AddStudentFormValues) => {
if (!user || !schoolId) {
toast.error("You must be logged in with a school account to invite students");
return;
}
setIsLoading(true);
try {
if (values.method === "email" && values.email) {
console.log("Creating email invitation for:", values.email);
const { data: { session } } = await supabase.auth.getSession();
if (!session) {
throw new Error("You must be logged in");
}
const { data, error } = await supabase.functions.invoke("invite-student", {
headers: {
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({
method: "email",
email: values.email,
}),
});
if (error) {
console.error("Error from invite-student function:", error);
throw error;
}
console.log("Invitation created:", data);
toast.success(`Invitation sent to ${values.email}`);
form.reset();
setGeneratedCode(""); // clear code if any previously generated
}
setRefreshTrigger((prev) => prev + 1);
} catch (error: any) {
console.error("Error inviting student:", error);
toast.error(error.message || "Failed to invite student");
} finally {
setIsLoading(false);
}
};
const copyInviteCode = () => {
if (!generatedCode) {
toast.error("No code available to copy");
return;
}
navigator.clipboard.writeText(generatedCode);
toast.success("Code copied to clipboard!");
};
const handleRefresh = () => {
setRefreshTrigger((prev) => prev + 1);
toast.success("Refreshing student invitations...");
};
const generateInviteCode = async () => {
setIsGeneratingCode(true);
try {
console.log("Calling invite-student edge function with method: code");
const { data: { session } } = await supabase.auth.getSession();
if (!session) {
throw new Error("You must be logged in");
}
const { data, error } = await supabase.functions.invoke("invite-student", {
headers: {
Authorization: `Bearer ${session.access_token}`,
},
body: JSON.stringify({ method: "code" }),
});
if (error) {
console.error("Error from invite-student function:", error);
throw new Error(error.message || "Failed to generate invitation code");
}
if (!data || !data.code) {
throw new Error("Invalid response received from server");
}
setGeneratedCode(data.code);
toast.success("Student invitation code generated");
setRefreshTrigger((prev) => prev + 1);
} catch (error: any) {
console.error("Error generating invite code:", error);
toast.error(error.message || "Failed to generate invitation code");
} finally {
setIsGeneratingCode(false);
}
};
return (
<div className="min-h-screen flex flex-col">
<Navbar />
<main className="flex-grow bg-learnable-super-light py-8">
<div className="container mx-auto px-4">
<div className="flex items-center gap-4 mb-6">
<Button variant="outline" size="sm" className="flex items-center gap-1" onClick={() => navigate("/admin")}>
<ArrowLeft className="h-4 w-4" />
Back to Admin
</Button>
<h1 className="text-3xl font-bold gradient-text">Student Management</h1>
</div>
<Card>
<CardHeader>
<CardTitle>Add New Student</CardTitle>
<CardDescription>Invite a student via email or generate a code</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="method"
render={({ field }) => (
<FormItem className="space-y-3">
<FormLabel>Method</FormLabel>
<FormControl>
<RadioGroup
onValueChange={field.onChange}
value={field.value}
className="flex flex-col space-y-1"
>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="email" />
</FormControl>
<FormLabel className="font-normal">Invite via Email</FormLabel>
</FormItem>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="code" />
</FormControl>
<FormLabel className="font-normal">Generate Invitation Code</FormLabel>
</FormItem>
</RadioGroup>
</FormControl>
<FormDescription>
{selectedMethod === "email"
? "The student will receive an email invitation to join your school."
: "You will receive a code that you can share with students."}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{selectedMethod === "email" && (
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input placeholder="student@example.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
{selectedMethod === "code" && (
<div>
<Button
type="button"
className="gradient-bg"
onClick={generateInviteCode}
disabled={isGeneratingCode}
>
<UserPlus className="mr-2 h-4 w-4" />
{isGeneratingCode ? "Generating..." : "Generate Code"}
</Button>
{generatedCode && (
<div className="p-4 mt-4 bg-muted rounded-lg">
<p className="font-semibold mb-2">Invitation Code:</p>
<div className="flex items-center gap-2">
<code className="bg-background p-2 rounded border flex-1 text-center text-lg font-mono">
{generatedCode}
</code>
<Button type="button" variant="outline" size="sm" onClick={copyInviteCode}>
<Copy className="h-4 w-4" />
</Button>
</div>
<p className="text-sm text-muted-foreground mt-2">
Share this code with students to join your school
</p>
</div>
)}
</div>
)}
{selectedMethod === "email" && (
<Button type="submit" className="gradient-bg" disabled={isLoading}>
<Mail className="mr-2 h-4 w-4" />
{isLoading ? "Sending..." : "Send Invitation"}
</Button>
)}
</form>
</Form>
</CardContent>
</Card>
<Card className="mt-6">
<CardHeader className="flex flex-row items-center justify-between">
<div>
<CardTitle>Student Invitations</CardTitle>
<CardDescription>Recent student invitations and codes</CardDescription>
</div>
<Button variant="outline" size="sm" onClick={handleRefresh} className="flex items-center gap-2">
<RefreshCw className="h-4 w-4" />
Refresh
</Button>
</CardHeader>
<CardContent>
{invites.length > 0 ? (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Email/Code</TableHead>
<TableHead>Created</TableHead>
<TableHead>Expires</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{invites.map((invite) => (
<TableRow key={invite.id}>
<TableCell>
{invite.email || (
<code className="bg-muted p-1 rounded text-xs font-mono">
{invite.code || "N/A"}
</code>
)}
</TableCell>
<TableCell>{new Date(invite.created_at).toLocaleDateString()}</TableCell>
<TableCell>{new Date(invite.expires_at).toLocaleDateString()}</TableCell>
<TableCell>
<span
className={`text-xs font-medium px-2 py-0.5 rounded ${
invite.status === "pending"
? "bg-yellow-100 text-yellow-800"
: invite.status === "accepted"
? "bg-green-100 text-green-800"
: "bg-red-100 text-red-800"
}`}
>
{invite.status.charAt(0).toUpperCase() + invite.status.slice(1)}
</span>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<p className="text-muted-foreground">No invitations found.</p>
)}
</CardContent>
<CardFooter>
<p className="text-xs text-muted-foreground">Student invitations expire after 7 days.</p>
</CardFooter>
</Card>
</div>
</main>
<Footer />
</div>
);
};
export default AdminStudents;
Final notes
Make sure your environment and Supabase backend accept these method values ("email" or "code").
This code requires that the Supabase invoke() function is from supabase-js v2+ and the Authorization header is forwarded with the current user’s access token.
The invite-student edge function must support receiving JSON body as string and parse it properly.
Let me know if you want me to help update your edge function or provide a working example of it!