Documentation

Troubleshooting

Common issues and solutions when using brease-next package.

Installation & Setup Issues

Issue: Cannot find module 'brease-next'

Symptoms:

  • Error: Cannot find module 'brease-next'
  • TypeScript errors for brease-next imports

Solutions:

  1. Install the package:

    npm install brease-next
    
  2. Verify installation:

    npm list brease-next
    
  3. Restart development server:

    # Stop the dev server (Ctrl+C)
    npm run dev
    
  4. Clear cache if needed:

    rm -rf node_modules package-lock.json
    npm install
    

Issue: TypeScript path alias not working

Symptoms:

  • Error: Cannot find module '@/lib/brease-config'
  • Import errors for @/ paths

Solutions:

  1. Verify tsconfig.json:

    {
      "compilerOptions": {
        "paths": {
          "@/*": ["./src/*"]
        }
      }
    }
    
  2. Restart TypeScript server in your IDE:

    • VS Code: Cmd+Shift+P → "TypeScript: Restart TS Server"

Environment & Configuration Issues

Issue: Environment variables not loading

Symptoms:

  • Error: Failed to fetch from : Unauthorized
  • Empty or undefined environment variables

Solutions:

  1. Check file naming:

    • Use .env.local for local development
    • Use .env.production for production builds
    • Never commit .env.local to version control
  2. Verify variable names:

    BREASE_BASE_URL=https://api.brease.io/v1
    BREASE_TOKEN=your_token_here
    BREASE_ENV=your_env_id
    BREASE_REVALIDATION_TIME=30
    
  3. Restart development server:

    # Stop the dev server (Ctrl+C)
    npm run dev
    
  4. Check Next.js environment variable access:

    • Only variables prefixed with NEXT_PUBLIC_ are available in client components
    • Server-side variables (without prefix) are only available in server components and API routes

Issue: Config not found in context

Symptoms:

  • Error: Cannot read properties of undefined (reading 'navigations')
  • Context data is undefined

Solutions:

  1. Verify contextData is configured:

    // src/lib/brease-config.ts
    export const contextData = {
      navigations: [
        { key: 'mainNavigation', id: 'nav-uuid...' },
      ],
      collections: [
        { key: 'news', id: 'col-uuid...' },
      ],
    };
    
  2. Check BreaseContext receives config:

    // src/app/layout.tsx
    import { BreaseContext } from 'brease-next';
    import { contextData } from '@/lib/brease-config';
    
    <BreaseContext config={contextData}>
      {children}
    </BreaseContext>
    

API & Data Fetching Issues

Issue: 401 Unauthorized error

Symptoms:

  • Error: Failed to fetch from https://...: Unauthorized
  • Status: 401

Solutions:

  1. Verify token is correct:

    • Check Brease dashboard for valid API token
    • Ensure token has proper permissions
  2. Check token format:

    BREASE_TOKEN=your_actual_token  # No quotes or extra spaces
    
  3. Verify Authorization header in brease-next package:

    • The package automatically adds Bearer prefix
    • Ensure BREASE_TOKEN environment variable is set

Issue: 404 Not Found for pages

Symptoms:

  • Pages return 404 in production
  • result.status === 404 from fetchPage()

Solutions:

  1. Check page slug format:

    // Correct:
    await fetchPage('/about');  // Include leading slash
    
    // Incorrect:
    await fetchPage('about');   // Missing leading slash
    
  2. Verify page exists in Brease:

    • Check Brease dashboard
    • Ensure page is published
    • Verify slug matches exactly (case-sensitive)
  3. Check environment:

    • Ensure BREASE_ENV matches the environment where pages are published

Issue: Stale content / cache not updating

Symptoms:

  • Changes in Brease don't appear on site
  • Content updates slowly or not at all

Solutions:

  1. Check revalidation time:

    BREASE_REVALIDATION_TIME=30  # Seconds
    
  2. Force revalidation in development:

    rm -rf .next
    npm run dev
    
  3. For production, use Next.js revalidation:

    // In page component
    export const revalidate = 30; // Seconds
    

Issue: Collection entries not found

Symptoms:

  • Error: Failed to load collection entry
  • Empty collection results

Solutions:

  1. Verify collection ID in config:

    // src/lib/brease-config.ts
    export const contextData = {
      navigations: [],
      collections: [
        { key: 'news', id: 'col-a01c8223-4e4a-40aa-90d9-70149e87322c' },
      ],
    };
    
  2. Check entry slug format:

    // Correct:
    await fetchEntryBySlug(collectionId, '/my-post');  // With leading slash
    
    // Incorrect:
    await fetchEntryBySlug(collectionId, 'my-post');   // Missing leading slash
    
  3. Verify entries are published:

    • Check Brease dashboard
    • Ensure collection has published entries

Build & Deployment Issues

Issue: Build fails with "Failed to fetch pages"

Symptoms:

  • Build error during generateStaticParams()
  • Error: Failed to fetch pages for static generation

Solutions:

  1. Check environment variables in build environment:

    • Vercel: Add variables in Project Settings → Environment Variables
    • Ensure variables are available for "Production" environment
  2. Verify network access:

    • Ensure build environment can access Brease API
    • Check firewall rules
  3. Add error handling:

    export async function generateStaticParams() {
      const result = await generateBreasePageParams();
    
      if (!result || result.length === 0) {
        console.warn('No pages found, returning empty params');
        return [];
      }
    
      return result;
    }
    

Issue: Redirects not working

Symptoms:

  • Redirects from Brease don't work on site
  • Build logs show "Failed to fetch redirects"

Solutions:

  1. Check import in next.config.ts:

    // Correct:
    import { fetchRedirects, type BreaseRedirect } from 'brease-next';
    
    // Incorrect (old approach):
    import { fetchRedirects } from '@/brease/server';
    
  2. Verify redirect format in Brease:

    • Source: /old-page
    • Destination: /new-page
    • Both should include leading slashes
  3. Check build output:

    npm run build
    # Look for "Redirects" section in output
    

Issue: Images not loading in production

Symptoms:

  • Images work locally but not in production
  • Error: Invalid src prop

Solutions:

  1. Verify remote patterns in next.config.ts:

    images: {
      remotePatterns: [
        {
          protocol: 'https',
          hostname: 's3.eu-central-1.amazonaws.com',
          pathname: '/**',
        }
      ]
    }
    
  2. Check image URLs from Brease:

    console.log('Image path:', breaseImage.path);
    // Should be full URL starting with https://
    
  3. Update remote patterns if using different CDN:

    images: {
      remotePatterns: [
        {
          protocol: 'https',
          hostname: 'your-cdn-domain.com',
          pathname: '/**',
        }
      ]
    }
    

Component & Rendering Issues

Issue: Section not rendering

Symptoms:

  • Console warning: No component found for section type: {type}
  • Section missing from page

Solutions:

  1. Check section map:

    // In brease-config.ts
    export const sectionMap = {
      hero: HeroSection,  // Key must match Brease section type exactly
    };
    
  2. Verify section type in Brease:

    • Check Brease dashboard
    • Section type is case-sensitive
    • Must match map key exactly
  3. Add section to map:

    import NewSection from '@/sections/new-section';
    
    export const sectionMap = {
      // ... existing sections
      newSection: NewSection,  // Add new section
    };
    

Issue: Rich text content not rendering

Symptoms:

  • HTML shows as plain text
  • Tags visible on page

Solutions:

  1. Use dangerouslySetInnerHTML:

    // Correct:
    <div dangerouslySetInnerHTML={{ __html: body }} />
    
    // Incorrect:
    <div>{body}</div>  // Renders as plain text
    
  2. Add CSS for rich text (optional):

    <div
      className="prose prose-lg"  // Tailwind Typography
      dangerouslySetInnerHTML={{ __html: content }}
    />
    

Context & Hook Issues

Issue: "useBrease must be used within a BreaseContext"

Symptoms:

  • Runtime error when using useBrease() hook
  • App crashes on load

Solutions:

  1. Verify BreaseContext wraps app:

    // In src/app/layout.tsx
    import { BreaseContext } from 'brease-next';
    import { contextData } from '@/lib/brease-config';
    
    export default function RootLayout({ children }) {
      return (
        <html>
          <body>
            <BreaseContext config={contextData}>
              {children}
            </BreaseContext>
          </body>
        </html>
      );
    }
    
  2. Check component is client component:

    'use client';  // Must be at top of file
    
    import { useBrease } from 'brease-next';
    

Issue: Cannot destructure navigation from useBrease

Symptoms:

  • Error: Cannot read property 'mainNavigation' of undefined
  • Navigation data not accessible

Solutions:

  1. Use new destructuring pattern:

    // Correct (new pattern):
    const { navigations } = useBrease();
    const { mainNavigation } = navigations;
    
    // Incorrect (old pattern):
    const { navigation } = useBrease();
    
  2. Check for undefined:

    const { navigations } = useBrease();
    const { mainNavigation } = navigations;
    
    if (!mainNavigation) {
      return null;  // Or loading state
    }
    
  3. Verify key matches config:

    // Config:
    export const contextData = {
      navigations: [
        { key: 'mainNavigation', id: 'nav-...' },  // Key here
      ],
    };
    
    // Usage:
    const { mainNavigation } = navigations;  // Must match key
    

Type & TypeScript Issues

Issue: Type errors with section props

Symptoms:

  • TypeScript error: Property 'title' does not exist
  • Section component has type errors

Solutions:

  1. Define proper interface:

    import type { BreaseMedia } from 'brease-next';
    
    interface HeroSectionProps {
      title: string;
      body: string;
      heroMedia: BreaseMedia;
    }
    
    export default function HeroSection({ title, body, heroMedia }: HeroSectionProps) {
      // ...
    }
    
  2. Make fields optional if they might not exist:

    interface HeroSectionProps {
      title: string;
      subtitle?: string;  // Optional
      heroMedia?: BreaseMedia;  // Optional
    }
    

Issue: Collection element type errors

Symptoms:

  • Error: Type 'unknown' is not assignable to...
  • Can't access collection entry fields

Solutions:

  1. Cast collection elements:

    const title = entry.elements.title as string;
    const content = entry.elements.content as string;
    const image = entry.elements.featuredImage as BreaseMedia;
    
  2. Create type for collection:

    interface BlogPostElements {
      title: string;
      content: string;
      excerpt: string;
      featuredImage: BreaseMedia;
      publishedAt: string;
    }
    
    // Use in component:
    const elements = entry.elements as unknown as BlogPostElements;
    const title = elements.title;
    

Image & Media Issues

Issue: Images not optimized

Symptoms:

  • Large image file sizes
  • Slow page load times

Solutions:

  1. Use BreaseImage component:

    import { BreaseImage } from 'brease-next';
    
    <BreaseImage breaseImage={media} />  // Automatically optimized
    
  2. Add responsive sizes:

    <Image
      src={media.path}
      alt={media.alt}
      width={media.width}
      height={media.height}
      sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
    />
    
  3. Use priority for above-fold images:

    <Image
      src={media.path}
      alt={media.alt}
      width={media.width}
      height={media.height}
      priority  // Loads immediately
    />
    

Issue: Missing alt text warning

Symptoms:

  • Console warning: Image elements must have an alt prop

Solutions:

  1. BreaseImage handles this automatically:

    // Fallback chain: breaseImage.alt → breaseImage.name → 'Image alt.'
    <BreaseImage breaseImage={media} />
    
  2. For custom Image usage:

    <Image
      src={media.path}
      alt={media.alt || media.name || 'Descriptive alt text'}
      width={media.width}
      height={media.height}
    />
    

Symptoms:

  • Navigation items don't link anywhere
  • Clicking navigation does nothing

Solutions:

  1. Check navigation item type:

    {mainNavigation.items.map((item) => {
      if (item.type === 'internal' && item.target) {
        // Internal link
        return <Link href={item.target.slug}>{item.value}</Link>;
      }
    
      if (item.url) {
        // External link
        return <a href={item.url}>{item.value}</a>;
      }
    
      return null;
    })}
    
  2. Verify navigation UUID in config:

    // In brease-config.ts
    export const contextData = {
      navigations: [
        { key: 'mainNavigation', id: 'nav-correct-uuid-here' },
      ],
    };
    

Issue: 404 on refresh for dynamic routes

Symptoms:

  • Pages work when navigating via Link
  • Pages 404 when refreshing or direct URL access

Solutions:

  1. Ensure generateStaticParams is called:

    export async function generateStaticParams() {
      return generateBreasePageParams();
    }
    
  2. Check build output:

    npm run build
    # Look for list of generated static pages
    
  3. Verify route file structure:

    src/app/
    └── [subpageSlug]/
        └── page.tsx  # Not [subpageSlug].tsx
    

Performance Issues

Issue: Slow page loads

Symptoms:

  • Pages take long to load
  • High Time to First Byte (TTFB)

Solutions:

  1. Implement static generation:

    export const dynamic = 'force-static';
    export async function generateStaticParams() {
      return generateBreasePageParams();
    }
    
  2. Reduce revalidation time:

    BREASE_REVALIDATION_TIME=3600  # 1 hour instead of 30 seconds
    
  3. Optimize images:

    • Use BreaseImage component
    • Add appropriate sizes
    • Use priority for above-fold images

Issue: Large bundle size

Symptoms:

  • Slow initial page load
  • Large JavaScript download

Solutions:

  1. Use dynamic imports for heavy components:

    import dynamic from 'next/dynamic';
    
    const HeavySection = dynamic(() => import('@/sections/heavy-section'), {
      loading: () => <div>Loading...</div>,
    });
    
  2. Check client components:

    • Only use 'use client' when necessary
    • Keep server components when possible
  3. Analyze bundle:

    npm install @next/bundle-analyzer
    # Configure in next.config.ts
    

Debugging Tips

Enable verbose logging

Add logging to track data flow:

export default async function Page() {
  const result = await fetchPage('/about');

  console.log('Fetch result:', {
    success: result.success,
    status: result.status,
    ...(result.success ? { pageData: result.data } : { error: result.error })
  });

  // ... rest of component
}

Check build output

Build output shows useful information:

npm run build

# Look for:
# - List of generated static pages
# - Redirects
# - Image optimization info
# - Route segments

Use React DevTools

Install React DevTools to inspect:

  • Component props
  • Context values
  • Render performance

Network tab

Check browser Network tab:

  • Verify API calls succeed
  • Check response data
  • Monitor cache headers

Getting Help

If you're still experiencing issues:

  1. Check environment variables - Most issues stem from incorrect configuration
  2. Review error messages carefully - They often indicate the exact problem
  3. Compare with sample project - Reference the working implementation
  4. Check Brease API directly - Use tools like Postman to test API endpoints
  5. Review Next.js docs - Many issues relate to Next.js concepts, not the package

Common Gotchas

  1. Leading slashes: Always include leading slashes in slugs (/about, not about)
  2. Server vs client: Environment variables without NEXT_PUBLIC_ only work server-side
  3. Type casting: Collection elements are untyped, always cast them
  4. Client directive: 'use client' must be first line in file
  5. Case sensitivity: Section types and slugs are case-sensitive
  6. Build cache: Delete .next folder if changes don't appear
  7. Import paths: All imports from 'brease-next' package, not local paths
  8. Context pattern: Use navigations and collections objects with destructuring

Preventive Best Practices

  1. Always check success before accessing data:

    if (!result.success) {
      // Handle error
    }
    
  2. Use TypeScript strictly:

    • Enable strict mode in tsconfig.json
    • Define interfaces for all section props
    • Type cast collection elements
  3. Test error states:

    • Test with invalid slugs
    • Test with missing environment variables
    • Test network failures
  4. Monitor build output:

    • Check for warnings
    • Verify expected number of pages generated
    • Confirm redirects are applied
  5. Use static generation when possible:

    • Better performance
    • Better SEO
    • Reduced API load
  6. Configure context data properly:

    • Define all navigations and collections upfront
    • Use descriptive keys that match your usage
    • Verify UUIDs are correct
Previous
Examples