question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Plans to support Next.js 13 - /app directory

See original GitHub issue

The problem

Next JS just release their v13 publicly. As seen in their docs, emotion has not yet added support.

Is there any plan to add support in the near future?

Thanks.

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:154
  • Comments:41 (10 by maintainers)

github_iconTop GitHub Comments

43reactions
emmatowncommented, Oct 27, 2022

We may want to add an explicit API for this but this works today:

// app/emotion.tsx
"use client";
import { CacheProvider } from "@emotion/react";
import createCache from "@emotion/cache";
import { useServerInsertedHTML } from "next/navigation";
import { useState } from "react";

export default function RootStyleRegistry({
  children,
}: {
  children: JSX.Element;
}) {
  const [cache] = useState(() => {
    const cache = createCache({ key: "css" });
    cache.compat = true;
    return cache;
  });

  useServerInsertedHTML(() => {
    return (
      <style
        data-emotion={`${cache.key} ${Object.keys(cache.inserted).join(" ")}`}
        dangerouslySetInnerHTML={{
          __html: Object.values(cache.inserted).join(" "),
        }}
      />
    );
  });

  return <CacheProvider value={cache}>{children}</CacheProvider>;
}

// app/layout.tsx
import RootStyleRegistry from "./emotion";

export default function RootLayout({ children }: { children: JSX.Element }) {
  return (
    <html>
      <head></head>
      <body>
        <RootStyleRegistry>{children}</RootStyleRegistry>
      </body>
    </html>
  );
}

// app/page.tsx
/** @jsxImportSource @emotion/react */
"use client";

export default function Page() {
  return <div css={{ color: "green" }}>something</div>;
}
23reactions
Andaristcommented, Nov 18, 2022

After talking with the Next.js team and helping them recognize the problem with useServerInsertedHTML and Suspense that issue has been fixed in https://github.com/vercel/next.js/pull/42293

With that fix Emotion roughly works in the /app if you do this:

"use client";
import { CacheProvider } from "@emotion/react";
import createCache from "@emotion/cache";
import { useServerInsertedHTML } from "next/navigation";
import { useState } from "react";

export default function RootStyleRegistry({
  children,
}: {
  children: JSX.Element;
}) {
  const [{ cache, flush }] = useState(() => {
    const cache = createCache({ key: "my" });
    cache.compat = true;
    const prevInsert = cache.insert;
    let inserted: string[] = [];
    cache.insert = (...args) => {
      const serialized = args[1];
      if (cache.inserted[serialized.name] === undefined) {
        inserted.push(serialized.name);
      }
      return prevInsert(...args);
    };
    const flush = () => {
      const prevInserted = inserted;
      inserted = [];
      return prevInserted;
    };
    return { cache, flush };
  });

  useServerInsertedHTML(() => {
    const names = flush();
    if (names.length === 0) return null;
    let styles = "";
    for (const name of names) {
      styles += cache.inserted[name];
    }
    return (
      <style
        data-emotion={`${cache.key} ${names.join(" ")}`}
        dangerouslySetInnerHTML={{
          __html: styles,
        }}
      />
    );
  });

  return <CacheProvider value={cache}>{children}</CacheProvider>;
}

(kudos to the @emmatown for providing this implementation)

We need to figure out the exact APIs for handling this within Emotion but conceptually the thing would end up being very similar - you just won’t have to override cache.insert in the future and we’ll provide this new kind of the flush in Emotion itself.

Note that you should only use Emotion with the so-called client components (we might add "use client"; directive to our files to make this obvious). They can render on the server just fine - for the initial SSRed/streamed HTML but server “refetches” won’t render them on the server, they might be rendered on the client when the “refetch” response comes back. This is not Emotion’s limitation - it’s a limitation for all CSS-in-JS libs like Emotion (including Styled Components, styled-jsx and more)

Read more comments on GitHub >

github_iconTop Results From Across the Web

App Directory Roadmap - Next.js beta docs
Section Feature Supported React 18 Server Components ✓ Default React 18 Client Components ✓ Opt‑in React 18 Shared Components 🏗️
Read more >
i18n with Next.js 13 and app directory - DEV Community ‍ ‍
js 13 which introduced the new app directory. It includes support for Layouts, Server Components, Streaming and Support for Data Fetching.
Read more >
NextJS 13 - First Look at the /app Folder & Complete Demo
NextJS 13 introduces the beta version of the brand-new / app folder support. This folder allows you to build NextJS apps in a...
Read more >
Next.js 13: Working with the new app directory - LogRocket Blog
While still supporting the same file system-based routing, which uses the pages directory, the new app directory introduces the concepts of ...
Read more >
How the App Directory Works in Next.js 13 - MakeUseOf
Next.js 13 introduced a new routing system using the app directory. Next.js 12 already provided an easy way of handling routes through ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found