How to redirect using trpc nextjs base on db query?

This seems less intuitive than it should've. I'm trying to check if a user is new, if it is then I redirect them to a new page to setup their profile. So far I've tried to do it with react, trpc, middleware, it doesn't seem to work. the problem with react is I can't get the current session using clerk with useAuth, and I'd like to redirect before the page starts rendering,. So I thought I have to go to trpc with the private procecdure where I check if a user is logged in, like trpc, but I can't return any redirect objects because that doesn't fit the middleware return type. if I use non trpc middle ware where the params are just req and res, I can't get the current user session.
7 Replies
Neto
Neto14mo ago
You can check at middleware level if the user has its necessary information
低级黑小明👑
But how do I redirect at the server after I checked it
Neto
Neto14mo ago
// if the user is not signed in redirect them to the sign in page.
const { userId } = getAuth(request)

if (!userId) {
// redirect the users to /pages/sign-in/[[...index]].ts

const signInUrl = new URL('/sign-in', request.url)
signInUrl.searchParams.set('redirect_url', request.url)
return NextResponse.redirect(signInUrl)
}

// check what you want here
if(something){
const somePageUrl = new URL('/some-page', request.url)
return NextResponse.redirect(somePageUrl)
}

return NextResponse.next()
// if the user is not signed in redirect them to the sign in page.
const { userId } = getAuth(request)

if (!userId) {
// redirect the users to /pages/sign-in/[[...index]].ts

const signInUrl = new URL('/sign-in', request.url)
signInUrl.searchParams.set('redirect_url', request.url)
return NextResponse.redirect(signInUrl)
}

// check what you want here
if(something){
const somePageUrl = new URL('/some-page', request.url)
return NextResponse.redirect(somePageUrl)
}

return NextResponse.next()
低级黑小明👑
Thanks for your help. so I don’t touch trpc at all? This is all done in nextjs? Because I can’t return next response.redirect inside trpc calls. I’d like to replace all api with trpc calls,
Neto
Neto14mo ago
yes
低级黑小明👑
you're a life saver.! I know it works, but maybe it's because of my environment setup, I get this werird error : const signInUrl = new URL('/', "http://localhost:3000") signInUrl.searchParams.set('redirect_url', "http://localhost:3000") return NextResponse.redirect(signInUrl);
低级黑小明👑
idk if I fixed it but apparently I can't return nextResponse, I can only return nextapiresponse, but I don't know why it works for other people
Want results from more Discord servers?
Add your server
More Posts