rovrav
rovrav
Explore posts from servers
TTCTheo's Typesafe Cult
Created by rovrav on 9/12/2023 in #questions
Use trpc on nextJS api route?
Hence the appRouter import
7 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/12/2023 in #questions
Use trpc on nextJS api route?
import { TRPCError } from '@trpc/server';
import { getHTTPStatusCodeFromError } from '@trpc/server/http';
import { appRouter } from '~/server/routers/_app';
import type { NextApiRequest, NextApiResponse } from 'next';
 
type ResponseData = {
data?: {
postTitle: string;
};
error?: {
message: string;
};
};
 
export default async (
req: NextApiRequest,
res: NextApiResponse<ResponseData>,
) => {
/** We want to simulate an error, so we pick a post ID that does not exist in the database. */
const postId = `this-id-does-not-exist-${Math.random()}`;
 
const caller = appRouter.createCaller({});
 
try {
// the server-side call
const postResult = await caller.post.byId({ id: postId });
 
res.status(200).json({ data: { postTitle: postResult.title } });
} catch (cause) {
// If this a tRPC error, we can extract additional information.
if (cause instanceof TRPCError) {
// We can get the specific HTTP status code coming from tRPC (e.g. 404 for `NOT_FOUND`).
const httpStatusCode = getHTTPStatusCodeFromError(cause);
 
res.status(httpStatusCode).json({ error: { message: cause.message } });
return;
}
 
// This is not a tRPC error, so we don't have specific information.
res.status(500).json({
error: { message: `Error while accessing post with ID ${postId}` },
});
}
};
import { TRPCError } from '@trpc/server';
import { getHTTPStatusCodeFromError } from '@trpc/server/http';
import { appRouter } from '~/server/routers/_app';
import type { NextApiRequest, NextApiResponse } from 'next';
 
type ResponseData = {
data?: {
postTitle: string;
};
error?: {
message: string;
};
};
 
export default async (
req: NextApiRequest,
res: NextApiResponse<ResponseData>,
) => {
/** We want to simulate an error, so we pick a post ID that does not exist in the database. */
const postId = `this-id-does-not-exist-${Math.random()}`;
 
const caller = appRouter.createCaller({});
 
try {
// the server-side call
const postResult = await caller.post.byId({ id: postId });
 
res.status(200).json({ data: { postTitle: postResult.title } });
} catch (cause) {
// If this a tRPC error, we can extract additional information.
if (cause instanceof TRPCError) {
// We can get the specific HTTP status code coming from tRPC (e.g. 404 for `NOT_FOUND`).
const httpStatusCode = getHTTPStatusCodeFromError(cause);
 
res.status(httpStatusCode).json({ error: { message: cause.message } });
return;
}
 
// This is not a tRPC error, so we don't have specific information.
res.status(500).json({
error: { message: `Error while accessing post with ID ${postId}` },
});
}
};
7 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/12/2023 in #questions
Use trpc on nextJS api route?
Does this only work for the app router and not the pages router?
7 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/12/2023 in #questions
Use trpc on nextJS api route?
Wow, that's amazing
7 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
below is what I've been trying to do and figure out
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

fetch(`${API_BASE_URL}/api/user`)
.then(response => response.json())
.then(data => console.log(data));
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

fetch(`${API_BASE_URL}/api/user`)
.then(response => response.json())
.then(data => console.log(data));
but turns out you can just do this
fetch("/api/user")
.then(response => response.json())
.then(data => console.log(data));
fetch("/api/user")
.then(response => response.json())
.then(data => console.log(data));
18 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
I'm using vercel and vercel has an option to specify stating which env variables to use whether it's for production, testing or development. I did not know that you did not need a host url to call a nextJS api route. I've been putting the entire url when calling a nextJS api route this whole time.
18 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
The only solution I found was making an .env.development and .env.production and setting the host url that way. Can you use conditional logic in a .env file that would check NODE_ENV first then set NEXT_PUBLIC_HOST? How will you call the api route without knowing the host url to even check the NODE_ENV for setting?
18 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
the problem with that example is that process.env.NODE_ENV can't be accessed from the client side because it's not prefixed with NEXT_PUBLIC
18 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
Not sure if this is the Client side, but if so I'm not sure that process.env.NODE_ENV will work but correct me if I'm wrong
18 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
18 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
is that best done in a bifurcated env files? or just changing the NODE_ENV to be accessible from the client
18 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
I want to point the api route to localhost:3000 as the base url and thisismyurl.com for production
18 replies
TTCTheo's Typesafe Cult
Created by rovrav on 9/8/2023 in #questions
NODE_ENV exposed to the client? Is that okay?
yes, but is there a reason why it's made into a server variable? Right now I have a basic .env file but I'm trying to figure out if I have a env.development and env.production to separate out the url link to call an api route
18 replies
TTCTheo's Typesafe Cult
Created by zendev on 8/23/2023 in #questions
Alternative to Clerk for cross-platform app (Next.js / React Native + Expo)
It'd be a multi repo setup that way
11 replies
TTCTheo's Typesafe Cult
Created by zendev on 8/23/2023 in #questions
Alternative to Clerk for cross-platform app (Next.js / React Native + Expo)
Yeah, calling the api from the nextJS webapp. Haven't used expo before but that sounds right.
11 replies
TTCTheo's Typesafe Cult
Created by zendev on 8/23/2023 in #questions
Alternative to Clerk for cross-platform app (Next.js / React Native + Expo)
11 replies
TTCTheo's Typesafe Cult
Created by zendev on 8/23/2023 in #questions
Alternative to Clerk for cross-platform app (Next.js / React Native + Expo)
this is not the t3 turbo that has the mobile stuff integrated via expo. I can find you a repo for that but it uses a multi-schema db so you’ll have to change that.
11 replies
TTCTheo's Typesafe Cult
Created by rovrav on 7/2/2023 in #questions
Easy way to add rate limiter into t3 stack / trpc?
I'm getting errors with this
10 replies
TTCTheo's Typesafe Cult
Created by rovrav on 7/2/2023 in #questions
Easy way to add rate limiter into t3 stack / trpc?
export async function middleware(req: NextRequest) {
// We need to create a response and hand it to the supabase client to be able to modify the response headers.
const res = NextResponse.next();
// Create authenticated Supabase Client.
const supabase = createMiddlewareClient({ req, res });

// Rate limit by IP address
let ipAddress;

if (req && req?.ip) {
ipAddress = req.ip;
}

let success;

if (ipAddress) {
const rateLimitResult = await ratelimit.limit(ipAddress);
success = rateLimitResult.success;
}

// If rate limit is exceeded, respond with a 429 status code
if (!success) {
return NextResponse.error({ status: 429, statusText: "Too Many Requests" });
}

// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession();

// Check if user is on the signin page
if (req.nextUrl.pathname === "/signin" || req.nextUrl.pathname === "/") {
return res;
}

// Check auth condition
if (session) {
// Authentication successful, forward request to protected route.
return res;
}

// Auth condition not met, redirect to home page.
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = "/signin";
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname);
return NextResponse.redirect(redirectUrl);
}
export async function middleware(req: NextRequest) {
// We need to create a response and hand it to the supabase client to be able to modify the response headers.
const res = NextResponse.next();
// Create authenticated Supabase Client.
const supabase = createMiddlewareClient({ req, res });

// Rate limit by IP address
let ipAddress;

if (req && req?.ip) {
ipAddress = req.ip;
}

let success;

if (ipAddress) {
const rateLimitResult = await ratelimit.limit(ipAddress);
success = rateLimitResult.success;
}

// If rate limit is exceeded, respond with a 429 status code
if (!success) {
return NextResponse.error({ status: 429, statusText: "Too Many Requests" });
}

// Check if we have a session
const {
data: { session },
} = await supabase.auth.getSession();

// Check if user is on the signin page
if (req.nextUrl.pathname === "/signin" || req.nextUrl.pathname === "/") {
return res;
}

// Check auth condition
if (session) {
// Authentication successful, forward request to protected route.
return res;
}

// Auth condition not met, redirect to home page.
const redirectUrl = req.nextUrl.clone();
redirectUrl.pathname = "/signin";
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname);
return NextResponse.redirect(redirectUrl);
}
I'm trying to add a rate limiter to the middleware function, is this the best way?
10 replies
TTCTheo's Typesafe Cult
Created by zendev on 8/23/2023 in #questions
Alternative to Clerk for cross-platform app (Next.js / React Native + Expo)
I went with supabase myself. I wrote an article to help you set up with supabase instead of nextAuth.
https://dev.to/remusris/t3-stack-template-supabase-w-auth-db-and-shadcn-ui-basic-setup-2bl9 Github Link: https://github.com/remusris/t3_supabase_demo
11 replies