Unleash / unleash-client-nextjs

Unleash SDK for Next.js
28 stars 9 forks source link

Using Unleash App Router example leads to build errors #73

Closed raph90 closed 6 months ago

raph90 commented 6 months ago

Describe the bug

When I build my app, something about my Unleash code is leading to the following error:

SyntaxError: Unexpected token '<', "<html>
<h"... is not valid JSON
    at JSON.parse (<anonymous>)
    at parseJSONFromBytes (node:internal/deps/undici/undici:5584:19)
    at successSteps (node:internal/deps/undici/undici:5555:27)
    at fullyReadBody (node:internal/deps/undici/undici:1665:9)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async specConsumeBody (node:internal/deps/undici/undici:5564:7)
    at async M ) {

From looking around, it seems that this is because my page is being statically rendered (Next says its being dynamically rendered), and then I'm using cookies with my flags code.

The component causing the breakage looks like this:

import { Button, Flex } from '@mantine/core';
import Link from 'next/link';
import { evaluateFlags, flagsClient, getDefinitions } from '@unleash/nextjs';
import { cookies } from 'next/headers';
import { getSession } from '@/lib/dal';
// import WelcomeModalButton from '@/lib/pageRelated/home/WelcomeModal/WelcomeModalButton';
import HeaderMenu from './HeaderMenu';

export default async function HeaderLinks() {
  const session = await getSession();
  const cookieStore = cookies();
  const sessionId =
    cookieStore.get('unleash-session-id')?.value || `${Math.floor(Math.random() * 1_000_000_000)}`;

  const definitions = await getDefinitions({
    fetchOptions: {
      next: { revalidate: 5 }, // invalidate cache every 5 seconds
    },
  });

  const { toggles } = await evaluateFlags(definitions, {
    sessionId,
  });
  const flags = flagsClient(toggles);

  const launch = flags.isEnabled('launch_gg');
  return launch ? (
    <Flex align="center" gap="md">
      {session && (
        <Button component={Link} href="/games/new">
          new game
        </Button>
      )}

      {session ? (
        <HeaderMenu user={session.user} />
      ) : (
        <Button component={Link} href="/sign-in">
          sign in
        </Button>
      )}
    </Flex>
  ) : (
    <Flex align="center" gap="md"></Flex>
  );
}

I had previously moved my Unleash code into a function, but moved it back into the body of the component to see if it would fix the problem, which it doesn't.

I'm using standalone output, my next config looks like this:

const bundleAnalyzer = require('@next/bundle-analyzer');

const withBundleAnalyzer = bundleAnalyzer({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({
  reactStrictMode: false,
  eslint: {
    ignoreDuringBuilds: true,
  },
  experimental: {
    optimizePackageImports: ['@mantine/core', '@mantine/hooks', '@mantine/form', '@mantine/dates'],
    serverActions: {
      allowedOrigins: ['localhost:3000'],
    },
    serverComponentsExternalPackages: ['pino', 'pino-pretty', 'pino-datadog-transport'],
  },
  output: 'standalone',
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'my-app.com',
        port: '',
        pathname: '/**',
      },
    ],
  },
});

The issue might be that the component above (a Server component) is being rendered as a child of a client component (this is a legal pattern acording to the NextJS docs), but I'm not sure. This error only occurs in production, not development.

Steps to reproduce the bug

Create a new next project with the above config. Build the app (next build), then run with "start": "export $(cat .env.local | xargs) && node .next/standalone/server.js"

Use Unleash in an RSC. The error should appear.

Expected behavior

I'd expect the app to render.

Logs, error output, etc.

No response

Screenshots

No response

Additional context

No response

Unleash version

1.4.3

Subscription type

None

Hosting type

Self-hosted

SDK information (language and version)

"@unleash/nextjs": "^1.4.3",

raph90 commented 6 months ago

Closing this - I bumped the memory on my VPS and the errors seem to have gone away. I think what was happening is that Unleash wasn't available because there wasn't enough memory, and was sending back some sort of html error response.