N
Nuxt7mo ago
roobr

Nuxt 3 Supabase serverSupabaseUser(event) returning NULL

Hello, I am currently having issues getting the client via the serverSuperbaseUser function. Can you please let me know if I am handling fetching a user on server api correctly? sometimes it works and sometimes it returns null even when logged in using supabase auth I have tried changing cookie options to get it to work correctly but doesn't seem to function all the time. Code for reference:
import { PrismaClient } from '@prisma/client'
import { serverSupabaseUser } from '#supabase/server';
import { ref } from 'vue'

const prisma = new PrismaClient()
const type = ref("")

export default defineEventHandler(async (event) => {
type.value = event.context.params.type
console.log(type)
if (!(type.value === 'agency' || type.value === 'general' || type.value === 'admin')) {
throw createError({ statusCode: 400, message: 'Invalid type' })
}
// add in check to see if admin is authorised
if (type.value === 'admin') {
const user = await serverSupabaseUser(event)
if (!user) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
const admin = await prisma.admin_users.findFirst({
where: {
user_id: user.id,
},
})
if (!admin) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
}
try {
const items = await prisma.items.findMany({
include: {
item_categories_item_categories_item_idTocategories: {
include: {
categories_item_categories_category_idTocategories: {
select: {
id: true,
name: true,
},
},
},
},
item_subcategory_item_subcategory_item_idTosubcategories: {
include: {
subcategories_item_subcategory_subcat_idTosubcategories: {
select: {
id: true,
name: true,
main_category: true,
},
},
},
},
},
})
const categories = await prisma.categories.findMany(
{
select: {
id: true,
name: true,
agency_category: true,
general_category: true,
},
orderBy: {
list_order: 'asc',
},
}
)
const subcategories = await prisma.subcategories.findMany(
{
select: {
id: true,
name: true,
main_category: true,
},
}
)

const formattedItems = items
.map((item) => {
const category = item.item_categories_item_categories_item_idTocategories?.categories_item_categories_category_idTocategories
if (!category) {
console.warn('Category details are missing for item:', item)
return null
}

const subcategory = item.item_subcategory_item_subcategory_item_idTosubcategories?.subcategories_item_subcategory_subcat_idTosubcategories
const subCategoryName = subcategory ? subcategory.name : 'Other'

return {
id: item.item_id,
title: item.item_title,
description: item.item_description,
image: item.item_image,
melb_stock: item.melb_stock,
syd_stock: item.syd_stock,
qld_stock: item.qld_stock,
total_stock: item.total_stock,
category: category.name,
categoryId: category.id,
subCategories: [subCategoryName],
agency_item: item.agency_item,
general_item: item.general_item,
...((type.value === 'agency' || type.value === 'admin') && { price: item.rate })
}
})
.filter((item) => item !== null)

return { formattedItems, categories, subcategories }
} catch (error) {
console.error('Failed to fetch items:', error)
throw createError({ statusCode: 500, message: 'Failed to fetch items' })
}
})
import { PrismaClient } from '@prisma/client'
import { serverSupabaseUser } from '#supabase/server';
import { ref } from 'vue'

const prisma = new PrismaClient()
const type = ref("")

export default defineEventHandler(async (event) => {
type.value = event.context.params.type
console.log(type)
if (!(type.value === 'agency' || type.value === 'general' || type.value === 'admin')) {
throw createError({ statusCode: 400, message: 'Invalid type' })
}
// add in check to see if admin is authorised
if (type.value === 'admin') {
const user = await serverSupabaseUser(event)
if (!user) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
const admin = await prisma.admin_users.findFirst({
where: {
user_id: user.id,
},
})
if (!admin) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
}
try {
const items = await prisma.items.findMany({
include: {
item_categories_item_categories_item_idTocategories: {
include: {
categories_item_categories_category_idTocategories: {
select: {
id: true,
name: true,
},
},
},
},
item_subcategory_item_subcategory_item_idTosubcategories: {
include: {
subcategories_item_subcategory_subcat_idTosubcategories: {
select: {
id: true,
name: true,
main_category: true,
},
},
},
},
},
})
const categories = await prisma.categories.findMany(
{
select: {
id: true,
name: true,
agency_category: true,
general_category: true,
},
orderBy: {
list_order: 'asc',
},
}
)
const subcategories = await prisma.subcategories.findMany(
{
select: {
id: true,
name: true,
main_category: true,
},
}
)

const formattedItems = items
.map((item) => {
const category = item.item_categories_item_categories_item_idTocategories?.categories_item_categories_category_idTocategories
if (!category) {
console.warn('Category details are missing for item:', item)
return null
}

const subcategory = item.item_subcategory_item_subcategory_item_idTosubcategories?.subcategories_item_subcategory_subcat_idTosubcategories
const subCategoryName = subcategory ? subcategory.name : 'Other'

return {
id: item.item_id,
title: item.item_title,
description: item.item_description,
image: item.item_image,
melb_stock: item.melb_stock,
syd_stock: item.syd_stock,
qld_stock: item.qld_stock,
total_stock: item.total_stock,
category: category.name,
categoryId: category.id,
subCategories: [subCategoryName],
agency_item: item.agency_item,
general_item: item.general_item,
...((type.value === 'agency' || type.value === 'admin') && { price: item.rate })
}
})
.filter((item) => item !== null)

return { formattedItems, categories, subcategories }
} catch (error) {
console.error('Failed to fetch items:', error)
throw createError({ statusCode: 500, message: 'Failed to fetch items' })
}
})
3 Replies
Menttis
Menttis6mo ago
Hi, did you ever get this sorted? I'm having the same issue, trying to secure server routes with middleware:
import { serverSupabaseClient } from '#supabase/server'
import { serverSupabaseUser } from '#supabase/server'
import { serverSupabaseSession } from '#supabase/server'

export default defineEventHandler(async (event) => {
const supabase = await serverSupabaseClient(event);
const user = await serverSupabaseUser(event)
const session = await serverSupabaseSession(event)

console.log('USER ' + JSON.stringify(user)) // Returns null
console.log('SESSION' + JSON.stringify(session)); // Returns null

})
import { serverSupabaseClient } from '#supabase/server'
import { serverSupabaseUser } from '#supabase/server'
import { serverSupabaseSession } from '#supabase/server'

export default defineEventHandler(async (event) => {
const supabase = await serverSupabaseClient(event);
const user = await serverSupabaseUser(event)
const session = await serverSupabaseSession(event)

console.log('USER ' + JSON.stringify(user)) // Returns null
console.log('SESSION' + JSON.stringify(session)); // Returns null

})
roobr
roobrOP6mo ago
No resolution yet, I have added in some print statements to help see if its cookies or not, I will keep you updated
Menttis
Menttis6mo ago
Ok, thanks. I ended up doing the checks in the server API post file. Just passed the role and jwt values from Pinia state to there in body. But middleware would be more elegant solution.
Want results from more Discord servers?
Add your server