koko#1337
koko#1337
TtRPC
Created by entropy on 5/25/2023 in #❓-help
Issue with trpc fetch when trying to pass Clerk auth to context
cool, glad I was of help 🙂
53 replies
TtRPC
Created by entropy on 5/25/2023 in #❓-help
Issue with trpc fetch when trying to pass Clerk auth to context
in my case any TRPC calls would happen post auth, so I added the auth check in the middleware, but feel free to remove that if your case differs
53 replies
TtRPC
Created by entropy on 5/25/2023 in #❓-help
Issue with trpc fetch when trying to pass Clerk auth to context
and for the middleware:
import { getAuth, withClerkMiddleware } from '@clerk/nextjs/server'

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

// Set the paths that don't require the user to be signed in
const publicPaths = ['/sign-in*', '/sign-up*', '/landing'],
isPublic = (path: string) =>
publicPaths.find((x) => path.match(new RegExp(`^${x}$`.replace('*$', '($|/)')))),
authedEndpoints = ['/api/trpc*'],
isAuthedEndpoint = (path: string) =>
authedEndpoints.find((x) => path.match(new RegExp(`^${x}$`.replace('*$', '($|/)'))))

export default withClerkMiddleware((request: NextRequest) => {
if (isPublic(request.nextUrl.pathname)) {
return NextResponse.next()
}
// if the user is not signed in redirect them to the sign in page.
const { userId } = getAuth(request)

// prevent trpc calls if user not authed
if (isAuthedEndpoint(request.nextUrl.pathname) && !userId) {
return NextResponse.json(
{
message: 'UNAUTHORIZED',
},
{ status: 400 }
)
}

if (!userId) {
// redirect the users to sign in
const signInUrl = new URL('/sign-in', request.url)
signInUrl.searchParams.set('redirect_url', request.url)
return NextResponse.redirect(signInUrl)
}

return NextResponse.next()
})

// Stop Middleware running on static files and public folder
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next
* - static (static files)
* - favicon.ico (favicon file)
* - public folder
* - trpc and api endpoints
*/
'/((?!static|.*\\..*|_next|favicon.ico).*)',
'/',
'/(api|trpc)(.*)',
],
}
import { getAuth, withClerkMiddleware } from '@clerk/nextjs/server'

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

// Set the paths that don't require the user to be signed in
const publicPaths = ['/sign-in*', '/sign-up*', '/landing'],
isPublic = (path: string) =>
publicPaths.find((x) => path.match(new RegExp(`^${x}$`.replace('*$', '($|/)')))),
authedEndpoints = ['/api/trpc*'],
isAuthedEndpoint = (path: string) =>
authedEndpoints.find((x) => path.match(new RegExp(`^${x}$`.replace('*$', '($|/)'))))

export default withClerkMiddleware((request: NextRequest) => {
if (isPublic(request.nextUrl.pathname)) {
return NextResponse.next()
}
// if the user is not signed in redirect them to the sign in page.
const { userId } = getAuth(request)

// prevent trpc calls if user not authed
if (isAuthedEndpoint(request.nextUrl.pathname) && !userId) {
return NextResponse.json(
{
message: 'UNAUTHORIZED',
},
{ status: 400 }
)
}

if (!userId) {
// redirect the users to sign in
const signInUrl = new URL('/sign-in', request.url)
signInUrl.searchParams.set('redirect_url', request.url)
return NextResponse.redirect(signInUrl)
}

return NextResponse.next()
})

// Stop Middleware running on static files and public folder
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next
* - static (static files)
* - favicon.ico (favicon file)
* - public folder
* - trpc and api endpoints
*/
'/((?!static|.*\\..*|_next|favicon.ico).*)',
'/',
'/(api|trpc)(.*)',
],
}
53 replies
TtRPC
Created by entropy on 5/25/2023 in #❓-help
Issue with trpc fetch when trying to pass Clerk auth to context
I implemented this the other week, this is how I added the clerk auth to the context
import { getAuth } from '@clerk/nextjs/server'
import { inferAsyncReturnType } from '@trpc/server'
import { CreateNextContextOptions } from '@trpc/server/adapters/next'

import { prisma } from '~/server/prisma'

/** Context creator for testing purposes */
const createInnerTRPCContext = ({ req }: CreateNextContextOptions) => {
return {
prisma,
auth: getAuth(req),
}
}

/**
* This is the actual context you will use in your router. It will be used to process every request
* that goes through your tRPC endpoint.
*
* @see https://trpc.io/docs/context
*/
export const createTRPCContext = (opts: CreateNextContextOptions) => {
return createInnerTRPCContext(opts)
}

export type TRPCContext = inferAsyncReturnType<typeof createTRPCContext>
import { getAuth } from '@clerk/nextjs/server'
import { inferAsyncReturnType } from '@trpc/server'
import { CreateNextContextOptions } from '@trpc/server/adapters/next'

import { prisma } from '~/server/prisma'

/** Context creator for testing purposes */
const createInnerTRPCContext = ({ req }: CreateNextContextOptions) => {
return {
prisma,
auth: getAuth(req),
}
}

/**
* This is the actual context you will use in your router. It will be used to process every request
* that goes through your tRPC endpoint.
*
* @see https://trpc.io/docs/context
*/
export const createTRPCContext = (opts: CreateNextContextOptions) => {
return createInnerTRPCContext(opts)
}

export type TRPCContext = inferAsyncReturnType<typeof createTRPCContext>
53 replies