N
Nuxt4d ago
Cordobes

supabase signup pass custom data

async function onSubmit(payload: FormSubmitEvent<Schema>) { try { const { error } = await supabase.auth.signUp({ email: payload.data.email, password: payload.data.password }) if (error) { toast.add({ title: 'Error', description: error.message, color: 'error' }) } else { toast.add({ title: 'Success', description: 'Logged in successfully', color: 'success' }) } } catch (error: any) { toast.add({ title: 'Error', description: error.message, color: 'error' }) } } how i can send username to supabase sign up auth
11 Replies
kapa.ai
kapa.ai4d ago
Hi @Cordobes. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To send a username to Supabase during sign up authentication, you need to include it in the options parameter of the signUp method. Based on the knowledge sources, I can provide guidance on how to handle form submissions in Nuxt and apply it to your Supabase authentication case. Here's how you can modify your code to include a username:
async function onSubmit(payload: FormSubmitEvent<Schema>) {
try {
const { error } = await supabase.auth.signUp({
email: payload.data.email,
password: payload.data.password,
options: {
data: {
username: payload.data.username
}
}
})
if (error) {
toast.add({ title: 'Error', description: error.message, color: 'error' })
} else {
toast.add({ title: 'Success', description: 'Logged in successfully', color: 'success' })
}
} catch (error: any) {
toast.add({ title: 'Error', description: error.message, color: 'error' })
}
}
async function onSubmit(payload: FormSubmitEvent<Schema>) {
try {
const { error } = await supabase.auth.signUp({
email: payload.data.email,
password: payload.data.password,
options: {
data: {
username: payload.data.username
}
}
})
if (error) {
toast.add({ title: 'Error', description: error.message, color: 'error' })
} else {
toast.add({ title: 'Success', description: 'Logged in successfully', color: 'success' })
}
} catch (error: any) {
toast.add({ title: 'Error', description: error.message, color: 'error' })
}
}
Make sure your form schema includes the username field. If you're using Zod for validation (as shown in some examples from the knowledge sources), your schema might look like:
const schema = z.object({
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Must be at least 8 characters'),
username: z.string().min(2, 'Username must be at least 2 characters')
})
const schema = z.object({
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Must be at least 8 characters'),
username: z.string().min(2, 'Username must be at least 2 characters')
})
Then in your form component, make sure to include a field for the username:
<UFormField label="Username" name="username">
<UInput v-model="state.username" />
</UFormField>
<UFormField label="Username" name="username">
<UInput v-model="state.username" />
</UFormField>
This approach follows the pattern shown in the form examples from the Nuxt UI documentation, where form data is collected and then processed in the submit handler. Note that the user metadata (like username) will be stored in Supabase's auth.users table in the user_metadata JSON column, which you can later access through the Supabase client. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1275808916168511508> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Cordobes
CordobesOP4d ago
i want to set display_name @kapa.ai i want to set display_name
kapa.ai
kapa.ai4d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Based on your previous question about sending custom data during Supabase signup, I understand you now want to specifically set a display_name instead of or in addition to a username. You can set the display_name in the same way, by including it in the data object within the options parameter of the signUp method:
async function onSubmit(payload: FormSubmitEvent<Schema>) {
try {
const { error } = await supabase.auth.signUp({
email: payload.data.email,
password: payload.data.password,
options: {
data: {
display_name: payload.data.display_name
}
}
})
if (error) {
toast.add({ title: 'Error', description: error.message, color: 'error' })
} else {
toast.add({ title: 'Success', description: 'Signed up successfully', color: 'success' })
}
} catch (error: any) {
toast.add({ title: 'Error', description: error.message, color: 'error' })
}
}
async function onSubmit(payload: FormSubmitEvent<Schema>) {
try {
const { error } = await supabase.auth.signUp({
email: payload.data.email,
password: payload.data.password,
options: {
data: {
display_name: payload.data.display_name
}
}
})
if (error) {
toast.add({ title: 'Error', description: error.message, color: 'error' })
} else {
toast.add({ title: 'Success', description: 'Signed up successfully', color: 'success' })
}
} catch (error: any) {
toast.add({ title: 'Error', description: error.message, color: 'error' })
}
}
Make sure your form includes a field for display_name and that it's properly validated in your schema if you're using validation. This custom user metadata will be stored in Supabase's auth system and can be accessed later through the user object. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1275808916168511508> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Cordobes
CordobesOP4d ago
@kapa.ai make this useasyncdata const authedFetch = async <T = any>(url: string, opts: any = {}) => { const headers = { ...opts.headers, Authorization: session.value?.access_token ? Bearer ${session.value.access_token} : undefined } const response = await useFetch<T>(url, { ...opts, headers }) console.log('Raw response:', response) // Handle Nuxt's useFetch response format if (response.data.value) { return response.data.value as T } return null }
kapa.ai
kapa.ai4d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I notice you're trying to create a custom authenticated fetch function using useFetch in Nuxt, but there are some issues with your implementation. Let me help you improve it based on the knowledge sources. The main problem is that you're using useFetch inside an async function, which doesn't preserve the reactivity that useFetch provides. According to the documentation, when creating a custom wrapper for useFetch, you should not await it in the composable as that can cause unexpected behavior. Here's a better implementation:
export function useAuthedFetch<T>(url: string, opts: UseFetchOptions<T> = {}) {
const { session } = useAuth() // Assuming you have a useAuth composable

return useFetch<T>(url, {
...opts,
headers: {
...opts.headers,
Authorization: session.value?.access_token
? `Bearer ${session.value.access_token}`
: undefined
}
})
}
export function useAuthedFetch<T>(url: string, opts: UseFetchOptions<T> = {}) {
const { session } = useAuth() // Assuming you have a useAuth composable

return useFetch<T>(url, {
...opts,
headers: {
...opts.headers,
Authorization: session.value?.access_token
? `Bearer ${session.value.access_token}`
: undefined
}
})
}
This approach follows the recommended pattern from the Nuxt documentation on custom useFetch, where you create a wrapper function that returns the result of useFetch directly, preserving its reactivity. If you need to use useAsyncData instead, you could do:
export function useAuthedAsyncData<T>(key: string, handler: () => Promise<T>, opts: UseAsyncDataOptions<T> = {}) {
const { session } = useAuth()

const wrappedHandler = async () => {
const headers = {
Authorization: session.value?.access_token
? `Bearer ${session.value.access_token}`
: undefined
}

// Use $fetch instead of useFetch here
return $fetch<T>(url, { ...opts, headers })
}

return useAsyncData(key, wrappedHandler, opts)
}
export function useAuthedAsyncData<T>(key: string, handler: () => Promise<T>, opts: UseAsyncDataOptions<T> = {}) {
const { session } = useAuth()

const wrappedHandler = async () => {
const headers = {
Authorization: session.value?.access_token
? `Bearer ${session.value.access_token}`
: undefined
}

// Use $fetch instead of useFetch here
return $fetch<T>(url, { ...opts, headers })
}

return useAsyncData(key, wrappedHandler, opts)
}
Remember that useFetch(url) is nearly equivalent to useAsyncData(url, () => $fetch(url)) as mentioned in the data fetching documentation. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1275808916168511508> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Cordobes
CordobesOP4d ago
const fetchComments = async () => { try { const data = await authedFetch<{ comments: Comment[] } | Comment[]>('/api/v1/comments', { method: 'GET', params: { sitekey, post_id: postId, hostname: referer } }) console.log('Fetched comments data:', data) // Check if data.comments exists (API might return an object with a comments property) const commentsArray = Array.isArray(data) ? data : (data as { comments: Comment[] })?.comments [] comments.value = commentsArray.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()) } catch (error) { console.error('Error fetching comments:', error) comments.value = [] } } fix this to useasyncdata @kapa.ai useasync data to response try { const data = await authedFetch<{ comments: Comment[] } | Comment[]>('/api/v1/comments', { method: 'GET', params: { sitekey, post_id: postId, hostname: referer } }) console.log('Fetched comments data:', data) // Check if data.comments exists (API might return an object with a comments property) const commentsArray = Array.isArray(data) ? data : (data as { comments: Comment[] })?.comments [] comments.value = commentsArray.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()) } catch (error) { console.error('Error fetching comments:', error) comments.value = [] } }
kapa.ai
kapa.ai4d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I'll help you convert your code to use useAsyncData for fetching comments. Based on our previous conversation about creating a custom authenticated fetch function, here's how you can implement this properly:
const { data: commentsData, error } = await useAsyncData('comments', async () => {
try {
return await $fetch<{ comments: Comment[] } | Comment[]>('/api/v1/comments', {
method: 'GET',
params: {
sitekey,
post_id: postId,
hostname: referer
},
headers: {
Authorization: session.value?.access_token
? `Bearer ${session.value.access_token}`
: undefined
}
})
} catch (error) {
console.error('Error fetching comments:', error)
return []
}
})

// Process the data once it's available
if (commentsData.value) {
console.log('Fetched comments data:', commentsData.value)
// Check if data.comments exists (API might return an object with a comments property)
const commentsArray = Array.isArray(commentsData.value)
? commentsData.value
: (commentsData.value as { comments: Comment[] })?.comments || []

comments.value = commentsArray.sort(
(a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
)
} else {
comments.value = []
}
const { data: commentsData, error } = await useAsyncData('comments', async () => {
try {
return await $fetch<{ comments: Comment[] } | Comment[]>('/api/v1/comments', {
method: 'GET',
params: {
sitekey,
post_id: postId,
hostname: referer
},
headers: {
Authorization: session.value?.access_token
? `Bearer ${session.value.access_token}`
: undefined
}
})
} catch (error) {
console.error('Error fetching comments:', error)
return []
}
})

// Process the data once it's available
if (commentsData.value) {
console.log('Fetched comments data:', commentsData.value)
// Check if data.comments exists (API might return an object with a comments property)
const commentsArray = Array.isArray(commentsData.value)
? commentsData.value
: (commentsData.value as { comments: Comment[] })?.comments || []

comments.value = commentsArray.sort(
(a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
)
} else {
comments.value = []
}
This implementation follows the recommended pattern from the Nuxt documentation on data fetching. The useAsyncData composable handles caching the response in the Nuxt payload, ensuring the data is available during hydration without re-fetching. If you want to create a reusable authenticated version of useAsyncData, you could follow the custom fetch composable pattern described in the Nuxt documentation:
export function useAuthedAsyncData<T>(key: string, url: string, options: any = {}) {
const { session } = useAuth() // Assuming you have a useAuth composable

return useAsyncData<T>(key, () => {
return $fetch<T>(url, {
...options,
headers: {
...options.headers,
Authorization: session.value?.access_token
? `Bearer ${session.value.access_token}`
: undefined
}
})
})
}
export function useAuthedAsyncData<T>(key: string, url: string, options: any = {}) {
const { session } = useAuth() // Assuming you have a useAuth composable

return useAsyncData<T>(key, () => {
return $fetch<T>(url, {
...options,
headers: {
...options.headers,
Authorization: session.value?.access_token
? `Bearer ${session.value.access_token}`
: undefined
}
})
})
}
Then you could use it like:
const { data: commentsData, error } = await useAuthedAsyncData<{ comments: Comment[] } | Comment[]>(
'comments',
'/api/v1/comments',
{
method: 'GET',
params: {
sitekey,
post_id: postId,
hostname: referer
}
}
)
const { data: commentsData, error } = await useAuthedAsyncData<{ comments: Comment[] } | Comment[]>(
'comments',
'/api/v1/comments',
{
method: 'GET',
params: {
sitekey,
post_id: postId,
hostname: referer
}
}
)
---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1275808916168511508> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?