Sveltekit Pages rendering differently between Preview and Production Builds, with the same code

I’m using Sveltekit and one of my pages renders fine on my machine, fine in Preview build, fine if I promote from Preview to production but not if it’s pushed straight to production.
My Production build is pulled from my Github and the build has a internal server error 500, and the only log is ’ GET
/units/newLease

TypeError: Cannot read properties of null (reading ‘num’)’
and then a traceback to the built pages. Can I access those pages?

If I push a preview build via the Vercel CLI the page loads correctly. If I then promote the build from Preview to Production the page loads correctly.

Here’s the +page.server.ts:

import  prisma from "$lib/server/prisma";

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore: it works
import type { Actions, PageServerLoad } from './$types';
import {superValidate, message } from 'sveltekit-superforms';
import z from 'zod';
import { zod } from 'sveltekit-superforms/adapters';
import { error, redirect } from "@sveltejs/kit";
import { ratelimit } from "$lib/server/redis";
import type { Unit } from 'prisma/prisma-client';

const newLeaseSchema = z.object({
   contactInfoId: z.string().min(23).max(30),
   unitPriceId: z.string().min(23).max(30),
   unitNum: z.string().min(23).max(30),
   organization: z.boolean(),
})


export const load:PageServerLoad = (async (event) =>{
   if(!event.locals.user){
      redirect(302, '/login')
   }
   const form = await superValidate(zod(newLeaseSchema));
   if(!event.locals.user.employee){
      const unitNum = event.url.searchParams.get('unitNum');
      let unit:Unit= {} as Unit;
      if(unitNum){
         console.log('newLease +page.server: unitNum:' + unitNum);
         unit = await prisma.unit.findUnique({
            where:{
               num:unitNum,
            }
         }).catch((err) =>{
            console.error(err);
            return error(404, 'Unit not found')
         }) || {} as Unit;
      }
      console.log('newLease +page.server: unit:' + unit);
      const address = await prisma.contactInfo.findMany({
         where:{
            userId:event.locals.user.id
         }
      }).catch((err) =>{
         console.error(err);
      });
      const unitPrice = await prisma.unitPricing.findFirst({
         where:{
            endDate: null,
            unitNum: unit.num
         }
      }).catch((err) =>{
         console.error(err);
      });
      return { form, unit, address, unitPrice };
   }
   return { form }
})


export const actions:Actions = {
   default: async (event) =>{
      const form = await superValidate(event.request, zod(newLeaseSchema));
      if(!form.valid){
         message(form, 'no good')
      }
      const { success, reset } = await ratelimit.register.limit(event.getClientAddress())
		if(!success) {
			const timeRemaining = Math.floor((reset - Date.now()) /1000);
			return message(form, `Please wait ${timeRemaining}s before trying again.`)
		}
      const customer = await prisma.user.findUniqueOrThrow({
         where:{
            id:event.locals.user?.id
         }
      }).catch((err) =>{
         console.error(err);
      })
      const unit = await prisma.unit.findFirst({
         where:{
            num:form.data.unitNum,
         }
      }).catch((err) =>{
         console.error(err);
      })
      const currentLease = await prisma.lease.findFirst({
         where:{
            unitNum: unit?.num,
            leaseEnded: null,
         }
      })
      if(currentLease){
         message(form, 'That unit is already leased');
      }
      const unitPrice = await prisma.unitPricing.findUniqueOrThrow({
         where:{
            unitPricingId:form.data.unitPriceId
         }
      }).catch((err) =>{
         console.error(err);
      })
      const contactInfoId = form.data.contactInfoId;
      const employees = await prisma.user.findMany({
         where:{
            employee: true,
         }
      })
      const employee = employees[Math.floor(Math.random()*employees.length)];
      const lease = await prisma.lease.create({
         data:{
            customerId: customer!.id,
            employeeId: employee.id,
            unitNum: form.data.unitNum,
            price: unitPrice!.price,
            contactInfoId,
            leaseEffectiveDate: new Date(),
         }
      });
      const invoice = await prisma.invoice.create({
         data:{
            price: lease.price,
            unitNum: lease.unitNum,
            invoiceAmount: lease.price,
            customerId: lease.customerId,
            leaseId: lease.leaseId,
            invoiceNotes:'Deposit for ' + lease.unitNum, 
         }
      })
      redirect(302, '/units/newLease/payDeposit?invoiceId=' + invoice.invoiceId)
   }
}

and the +page.svelte:

<script lang="ts">
   // @ts-ignore: it works
   import { PUBLIC_COMPANY_NAME } from '$env/static/public'
	import { superForm } from "sveltekit-superforms";
	import NameBlock from '$lib/userComponents/NameBlock.svelte';
	import Address from '$lib/userComponents/Address.svelte';
	import BasicUnitCustomer from '$lib/unitComponents/BasicUnitCustomer.svelte';
	
   // @ts-ignore: it works
   import type { PageData } from './$types';
	export let data:PageData
	const { form, errors, constraints, message, enhance } = superForm(data.form)
   import SuperDebug from 'sveltekit-superforms';
</script>

<svelte:head>
	<title>{PUBLIC_COMPANY_NAME} | Admin New Lease</title>
</svelte:head>

<SuperDebug data={$form} />

{#if $message}
<h3>{$message}</h3>
{/if}
{#if data.user}
<NameBlock nameBlock={data.user} />
{/if}
<form method="post" use:enhance>
{#if data.address}
   {#each data.address as address, index}
      <div class="flex">
         <Address address={address} />
         {#if index === 0}
            <input type="radio" name="contactInfoId" id={address.contactId} value={address.contactId} checked class="radio"/>
         {:else}
            <input type="radio" name="contactInfoId" id={address.contactId} value={address.contactId} class="radio"/>
         {/if}

      </div>
      {#if data.user?.organizationName}
         <div>
            <label for="orgainzation">This unit is being rented by an organization (Company, Non Profit, ect)
               <input type="checkbox" name="organization" id="organization" checked />
            </label>
         </div>
      {/if}
   {/each}
   
{:else}
   <a class="a" href="/register/addressFrom">Please add your address</a>
{/if}
{#if data.unit && data.unitPrice}
   <BasicUnitCustomer unit={data.unit} pricing={data.unitPrice} />
{/if}

{#if data.user && data.address && data.unitPrice}
   <input type="hidden" name="unitPriceId" id="unitPriceId" value={data.unitPrice.unitPricingId} />
   <input type="hidden" name="unitNum" id="unitNum" value={data.unit.num} />
   <button class="btn">All the above is correct, please email me a lease to sign</button>
{/if}
</form>

Hi, @uncle798! Welcome to the Vercel Community.

Thanks for your patience with this! That is odd, sounds like a bug. Could you try out the following:

  1. Check Logs: Are any specific error messages or stack traces that can provide more insight into the issue?

  2. Environment Variables: Make sure that all necessary environment variables are correctly set in your production environment. Sometimes, missing or incorrect environment variables can cause server errors.

  3. Build Configuration: Verify that your build configuration is correct and matches the configuration used in your local and preview environments. Differences in build settings can sometimes lead to unexpected errors in production. If you have a vercel.json, could you share this with us?

  4. Dependencies and Versions: Make that all dependencies are correctly installed and that there are no version mismatches between your local, preview, and production environments.

  5. Error Handling: Implement proper error handling in your server-side code to catch and log any errors that might be causing the 500 Internal Server Error. This can help in identifying the root cause of the issue.

Let us know how you get on! :smile:

I still haven’t found the error but it’s definitely my code as I tried Netlify and got the same problem. I haven’t specified a vercel.json or anything specific in my build configuration. The thing I’ve found that is different is this error happens on the github version of the site and not the CLI version.
Cookie “__vercel_live_token” has been rejected because it is in a cross-site context and its “SameSite” is “Lax” or “Strict”

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.