plyglt
plyglt
TTCTheo's Typesafe Cult
Created by plyglt on 2/16/2024 in #questions
Fonts not loading in production in Next14 (but working locally)
Worked on something entirely unrelated to fonts, and just now deployed and my custom font is just the system font. Any ideas here? It all looks fine on my local machine still, also when I do a build and run it locally. Tried it in different browsers as well. I deployed to production a couple of times now, but to no avail.
2 replies
TTCTheo's Typesafe Cult
Created by plyglt on 6/12/2023 in #questions
Anyone been able to get Google Tag Manager working with Next 13 (App Dir)?
I have been following this tutorial: https://dev.to/valse/how-to-setup-google-tag-manager-in-a-next-13-app-router-website-248p but it's not working for me. It recognises GTM being installed but pageview tags aren't firing. Any advice?
2 replies
TTCTheo's Typesafe Cult
Created by plyglt on 6/7/2023 in #questions
GenerateStaticParams + DynamicParams=false not Working in Next13
I am using generateStaticParams:
export async function generateStaticParams() {
let blogPosts = await prisma.posts.findMany({
where: {
category: "POLITICS",
},
});

const paths = blogPosts.map((text) => ({
slug: text.slug,
}));


return paths
}
export async function generateStaticParams() {
let blogPosts = await prisma.posts.findMany({
where: {
category: "POLITICS",
},
});

const paths = blogPosts.map((text) => ({
slug: text.slug,
}));


return paths
}
I want to only generate static pages for this route, and return a 404 when a user tries to visit something that does not exist at build time. So I am opting out of dynamic like so:
export default MyPage;
export const dynamic = 'force-static'
export const dynamicParams = false;
export default MyPage;
export const dynamic = 'force-static'
export const dynamicParams = false;
However, when I build this, this gives me a 404 for all my static routes. It works when I leave things dynamic and also in development, but not when I build the project. Next.JS also tells me that it recgonised the page and generated a static version, so it looks like it DID work:
├ ● /posts/[slug] 0 B 0 B
├ └ /posts/my-static-post
├ ○ /about 0 B 0 B
├ ● /posts/[slug] 0 B 0 B
├ └ /posts/my-static-post
├ ○ /about 0 B 0 B
However: when I visit it in production, it return a 404. Am I misunderstanding how this is supposed to be used?
2 replies
TTCTheo's Typesafe Cult
Created by plyglt on 5/14/2023 in #questions
Invalid Environment Variables In Brandnew Project
Just ran create-t3-app and just added one environment variable: Inside .env.mjs:
server: {
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(["development", "test", "production"]),
PAYPAL_SECRET: z.string(),
},
server: {
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(["development", "test", "production"]),
PAYPAL_SECRET: z.string(),
},
and in my .env:
DATABASE_URL="file:./db.sqlite"
PAYPAL_SECRET="123"
DATABASE_URL="file:./db.sqlite"
PAYPAL_SECRET="123"
However, I get:
❌ Invalid environment variables: { PAYPAL_SECRET: [ 'Required' ] } - error Failed to load next.config.mjs, see more info here https://nextjs.org/docs/messages/next-config-error Error: Invalid environment variables
What am I missing here?
7 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/25/2022 in #questions
Environment Variable Error when using prisma client directly in getStaticProps?
Normally using trpc, but just tried to make a prisma call in getStaticProps directly:
let data = await prisma.item.findUnique({
where: {
id: 'clc378c9p00zaz0194uz6o4u'
}
})
let data = await prisma.item.findUnique({
where: {
id: 'clc378c9p00zaz0194uz6o4u'
}
})
However, this gives me an error (server.mjs) :
Error: Invalid environment variables throw new Error("Invalid environment variables");
Not sure I understand why?
1 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/25/2022 in #questions
How to handle Failing Unique Constraints?
I am wondering how to handle those on a practical level. I have a frontend, where I can import lists of items into my database (prisma + mysql on planetscale). Right now, when a unique constraint fails, the whole import will fail. 1) Is there a way for me to tell my frontend, what item on the list failed the unique constraint? Right now I get:
Invalid `prisma.list.create()` invocation:
Unique constraint failed on the (not available)
at TRPCClientError.from (transformResult-106791
Invalid `prisma.list.create()` invocation:
Unique constraint failed on the (not available)
at TRPCClientError.from (transformResult-106791
2) Is there a way in the backend (i.e. prisma) where I can say that I want it to try to use a certain id, but if that fails (as a backup) generate a new id, instead of failing completely?
4 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/23/2022 in #questions
Do Planet Scales 'Dump' & 'Restore-Dump' via the CLI restore data + schemas or JUST the schemas?
Maybe a silly question: If I do a pscale database dump [database] [branch], will this save and backup the data, and then I can restore the database including all schemas + saved data via restore-dump <DATABASE_NAME> <BRANCH_NAME> ? Or will it just restore the schemas? ...just asking to make extra sure, I'm a little scared 😅
6 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/5/2022 in #questions
Do I need an Explicit Many-To-Many Relation, when I want to have an ordered List in MySQL (Prisma)?
I would love to use an implicit many to many relation, but I do need the user to be able to order their items (drag them up & down) - will I really need to create an extra table just to store the order? Or is there some way I can accomplish that with an implicit many-to-many relation?
1 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/4/2022 in #questions
vercel.json redirects not working in my Next.JS Project
Wondering why? It's just not working, giving me a 404 both on staging and when deployed to production. One is internal the other is an external redirect.
{
"redirects": [
{
"source": "/instagram",
"destination": "https://www.instagram.com/avocado.club/",
"permanent": true
},
{
"source": "/food/healthy/avocado",
"destination": "/food/avocado",
"permanent": true
}
]
}
{
"redirects": [
{
"source": "/instagram",
"destination": "https://www.instagram.com/avocado.club/",
"permanent": true
},
{
"source": "/food/healthy/avocado",
"destination": "/food/avocado",
"permanent": true
}
]
}
1 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/3/2022 in #questions
Optimistic Updates with TRPC (react-query)?
I am not sure how I would do optimistic updates with trpc? Is this "built-in" or do I have to use react-query's useQuery hook? So far, I am trying it like so, but it's not working:
const queryClient = useQueryClient();

const updateWord = trpc.word.update.useMutation({
onMutate: async newTodo => {
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
await queryClient.cancelQueries({ queryKey: ['text', 'getOne'] })

// Snapshot the previous value
const previousText = queryClient.getQueryData(['text', 'getOne'])

// Optimistically update to the new value
queryClient.setQueryData(['text', 'getOne'], old => old ? {...old, { title: "Hello" }} : undefined)

// Return a context object with the snapshotted value
return { previousText }
},
//...
const queryClient = useQueryClient();

const updateWord = trpc.word.update.useMutation({
onMutate: async newTodo => {
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
await queryClient.cancelQueries({ queryKey: ['text', 'getOne'] })

// Snapshot the previous value
const previousText = queryClient.getQueryData(['text', 'getOne'])

// Optimistically update to the new value
queryClient.setQueryData(['text', 'getOne'], old => old ? {...old, { title: "Hello" }} : undefined)

// Return a context object with the snapshotted value
return { previousText }
},
//...
Does this look like it should make sense? It's updating the value, but not optimistically.
4 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/2/2022 in #questions
Tell Zod to allow any fields in JSON (while in Development)?
I have a very large JS object I want to pass to trpc, through zod. Right now I just want to play around with the object a bit, before creating my zod schema. Is there a way to allow anything to be passed into zod (at least just in dev mode)? Or to just disable zod for the time being?
z.object({
id: z.string(),
data: z.object( // here i want to tell zod to allow any values)
})
z.object({
id: z.string(),
data: z.object( // here i want to tell zod to allow any values)
})
I know this is not the idea of zod at all, but would love to not have to build this crazy large schema right now only to throw it away later, because it's not really a finished/working thing right now.
3 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/2/2022 in #questions
How to configure T3 Stacks next.config + 'next-transpile-modules' (withTM) ?
I need to use next-transpile-modules in my t3 stack app, but not sure how to integrate it into my next.config file: The general recommendation is like this:
const withTM = require('next-transpile-modules')(['react-hook-mousetrap']);
module.exports = withTM({ /* Your Next.js config */ });
const withTM = require('next-transpile-modules')(['react-hook-mousetrap']);
module.exports = withTM({ /* Your Next.js config */ });
However, this doesn't work with the t3 next.config, though I'm sure I'm doing something wrong:
import { env } from "./src/env/server.mjs";

function defineNextConfig(config) {
return config;
}

const withTM = require('next-transpile-modules')(['react-hook-mousetrap']);

// module.exports = withTM({ /* Your Next.js config */ });

export default withTM(defineNextConfig({
reactStrictMode: true,
swcMinify: true,
// Next.js i18n docs: https://nextjs.org/docs/advanced-features/i18n-routing
i18n: {
locales: ["en"],
defaultLocale: "en",
},
webpack(config) {
config.resolve.fallback = {
...config.resolve.fallback, // if you miss it, all the other options in fallback, specified
// by next.js will be dropped. Doesn't make much sense, but how it is
fs: false, // the solution
};

return config;
},
}));
import { env } from "./src/env/server.mjs";

function defineNextConfig(config) {
return config;
}

const withTM = require('next-transpile-modules')(['react-hook-mousetrap']);

// module.exports = withTM({ /* Your Next.js config */ });

export default withTM(defineNextConfig({
reactStrictMode: true,
swcMinify: true,
// Next.js i18n docs: https://nextjs.org/docs/advanced-features/i18n-routing
i18n: {
locales: ["en"],
defaultLocale: "en",
},
webpack(config) {
config.resolve.fallback = {
...config.resolve.fallback, // if you miss it, all the other options in fallback, specified
// by next.js will be dropped. Doesn't make much sense, but how it is
fs: false, // the solution
};

return config;
},
}));
1 replies
TTCTheo's Typesafe Cult
Created by plyglt on 12/2/2022 in #questions
Passing URL Params to TRPC causes Error on First Render, as URL-Param is undefined
I am not sure if I am missing something, but I can't get this to work. I am getting some id passed down in my url params, and I want to pass down that id to trpc, to fetch some data from my database:
const Home: NextPage = () => {
const router = useRouter()

const { data, isLoading } = trpc.module.getOne.useQuery({
id: router.query.moduleId
});
//...
};

export default Home;
const Home: NextPage = () => {
const router = useRouter()

const { data, isLoading } = trpc.module.getOne.useQuery({
id: router.query.moduleId
});
//...
};

export default Home;
Now the problem seems to be that id isn't there on first render: the router will first have to get it etc., so I get a TRPC Client Error, as id at this time is undefined
TRPCClientError: [
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"id"
],
"message": "Required"
}
]
at TRPCClientError.from (transformResult-106791d7.mjs?2721:4:1)
at eval (httpBatchLink.mjs?9fec:190:40)
TRPCClientError: [
{
"code": "invalid_type",
"expected": "string",
"received": "undefined",
"path": [
"id"
],
"message": "Required"
}
]
at TRPCClientError.from (transformResult-106791d7.mjs?2721:4:1)
at eval (httpBatchLink.mjs?9fec:190:40)
What am I missing here?
11 replies
TTCTheo's Typesafe Cult
Created by plyglt on 11/30/2022 in #questions
What's a good service that helps scheduling cronjobs?
Looking into this right now. I need to trigger a few API calls once in a while. It's not a lot, so I'm thinking of getting a raspberry for this, but just curious what options are out there, if I want to regularly run a few functions?
10 replies
TTCTheo's Typesafe Cult
Created by plyglt on 11/23/2022 in #questions
How do I send sign-in links to New Users in Next-Auth, but disallow new registrations?
I am using the E-mail Provider with magic links in next-auth & I want users to be able to sign-in, when they already have an account, but not be able to sign-in when they don't: For new users, I want to manually check their applications and then send them a sign-in link. I am stuck as to how to do this though: The problem seems to be that sign-in & sign-up go via the same callback in next-auth: signIn(). There is no separate callback for signUp. Basically, what I want is: 1. Users who are already registered in the db can sign-in 2. New Users (who don't exist in the database yet) cannot sign-in / register via the sign-in callback. 3. When a new user signs up, I can send them a first-time sign-in link, that creates their profile in the db. From this point onwards, they can sign-in themselves Right now, what I've got is this:
async signIn(props) {
let { user, account, profile, email, credentials } = props;
const userExists = await prisma.user.findUnique({
where: {
email: user.email
}
});

if (!userExists) {
return false;
}

return true;
}
async signIn(props) {
let { user, account, profile, email, credentials } = props;
const userExists = await prisma.user.findUnique({
where: {
email: user.email
}
});

if (!userExists) {
return false;
}

return true;
}
This allows only users who already are in the database to sign-in. New users will see an error. But how can I now create new users in the backend / programmatically? I would like to have a setup like an admin dashboard, where I can simply type in an email and the user gets their sign-in link. The problem seems to be however that I would be using the very same signIn function, which would block creating the new user, if they don't exist in the database.
19 replies
TTCTheo's Typesafe Cult
Created by plyglt on 11/23/2022 in #questions
Is there a way to detect in the browser when the user connects a device to their machine?
Not without their permission, obviously, but it would be neat for users to be able to connect a device and have my app automatically detect it.
4 replies
TTCTheo's Typesafe Cult
Created by plyglt on 11/22/2022 in #questions
I want only registered users to be allowed to login & only admin can register new users? (Next-Auth)
I don't want users to sign up themselves. I first need to check something manually, only then do i want to send them a sign-in link. I do know how to prevent anyone from logging in:
async signIn({ user, account, profile, email, credentials }) {
const userExists = await prisma.user.findUnique({
where: {
email: user.email
}
});

if (!userExists) {
return false;
}

return true;
}
}
async signIn({ user, account, profile, email, credentials }) {
const userExists = await prisma.user.findUnique({
where: {
email: user.email
}
});

if (!userExists) {
return false;
}

return true;
}
}
However, I now want a functionality for myself / for our backend, where I can put in the users email address and they'll get a sign-in link. Not sure how I would do that. So basically, only already registered users should be allowed to sign-in, but registration should only be up to me or an admin.
33 replies
TTCTheo's Typesafe Cult
Created by plyglt on 11/19/2022 in #questions
Getting user IP in trpc without req object?
I used to get the users IP like so, just giving the package the req object:
const requestIp = require('request-ip');
const ip = requestIp.getClientIp(req);
const requestIp = require('request-ip');
const ip = requestIp.getClientIp(req);
With trpc, I don't have access to Next.JS's req object - how would I solve this now?
10 replies
TTCTheo's Typesafe Cult
Created by plyglt on 11/12/2022 in #questions
Module not found Can't resolve 'fs'
I am running into this error:
Module not found: Can't resolve 'fs'
> 1 | const fs = require("fs")
Module not found: Can't resolve 'fs'
> 1 | const fs = require("fs")
I read that it can be fixed like so in next.config:
module.exports = {
webpack: (config, { isServer }) => {
// Fixes npm packages that depend on `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
}
}

return config
}
}
module.exports = {
webpack: (config, { isServer }) => {
// Fixes npm packages that depend on `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
}
}

return config
}
}
Being the noob that I am, I don't know how to translate into the next.config in the t3 stack (next.config.mjs):
// @ts-check
import { env } from "./src/env/server.mjs";

/**
* Don't be scared of the generics here.
* All they do is to give us autocompletion when using this.
*
* @template {import('next').NextConfig} T
* @param {T} config - A generic parameter that flows through to the return type
* @constraint {{import('next').NextConfig}}
*/
function defineNextConfig(config) {
return config;
}

export default defineNextConfig({
reactStrictMode: true,
swcMinify: true,
// Next.js i18n docs: https://nextjs.org/docs/advanced-features/i18n-routing
i18n: {
locales: ["en"],
defaultLocale: "en",
},
});
// @ts-check
import { env } from "./src/env/server.mjs";

/**
* Don't be scared of the generics here.
* All they do is to give us autocompletion when using this.
*
* @template {import('next').NextConfig} T
* @param {T} config - A generic parameter that flows through to the return type
* @constraint {{import('next').NextConfig}}
*/
function defineNextConfig(config) {
return config;
}

export default defineNextConfig({
reactStrictMode: true,
swcMinify: true,
// Next.js i18n docs: https://nextjs.org/docs/advanced-features/i18n-routing
i18n: {
locales: ["en"],
defaultLocale: "en",
},
});
? Tried to do this, but didn't work:
function defineNextConfig(config) {
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config;
}
function defineNextConfig(config) {
if (!isServer) {
config.node = {
fs: 'empty'
}
}
return config;
}
2 replies
TTCTheo's Typesafe Cult
Created by plyglt on 10/24/2022 in #questions
Trpc & non-consistent JSON Field Attributes in MySQL
Just getting used to trpc & the t3 stack. Say I have a standard procedure:
update: t.procedure
.input(z.object({
id: z.string(),
type: z.string(),
content: z.object({ title: z.string() }).nullish()
}).nullish())
update: t.procedure
.input(z.object({
id: z.string(),
type: z.string(),
content: z.object({ title: z.string() }).nullish()
}).nullish())
Now what I am interested in is the content attribute. In my mysql schema, that content field is a JSON field. Depending on the type field, it will contain different values. For example. If type is blogPost, it will contain attributes like title & category, but if the type is set to landingPage those attributes will change. (just an example to make it more straightforward, my use case isn't about blogPosts etc.) Now trpc expects me to tell it what the object looks like: e.g.: there is a title, which is a string. But what if my landingPage type looks totally different, and, say, doesn't have a title?
2 replies