Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE:

The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here



import Link from "next/link";
import StyledHero from "./Hero.style";

const Hero = () => {
    return (
        <StyledHero>
            <h1>Stowarzyszenie Juz Lepiej</h1>
            <h2>Przybywam w celu:</h2>
            <Link about="Panel wolontariusza" href={"/volunteer"}>Uzyskania pomocy</Link>
            <Link about="Panel podopiecznego" href={"/mentee"}>Niesienia pomocy</Link>
            
        </StyledHero>
    )
};

export default Hero;


import styled from "styled-components";

const StyledHero = styled.main`
    width: 100%;
    height: auto;
    padding: 10em;

`
export default StyledHero;

I am encountering an error when using Styled Component. How do I use StyledComponents with SSR in Next13? None of the solutions I have found are working. However, changing <StyledHero> to <main></main> fixes the issue.

I have tried configuring .babelrc as follows:

{
    "presets": [
      "next/babel"
    ],
    "plugins": [
     [
       "styled-components",
       {
          "ssr": true,
          "displayName": true,
          "preprocess": false
        }
     ]
    ]
}

This is my package.json configuration:

{
  "name": "mentalhealthcharity",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@next/font": "13.2.4",
    "@types/node": "18.15.11",
    "@types/react": "18.0.31",
    "@types/react-dom": "18.0.11",
    "@types/styled-components": "^5.1.26",
    "eslint": "8.37.0",
    "eslint-config-next": "13.2.4",
    "next": "13.2.4",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "styled-components": "^5.3.9",
    "typescript": "5.0.2",
    "zustand": "^4.3.6"
  },
  "devDependencies": {
    "babel-plugin-styled-components": "^2.0.7"
  }
}

Answer №1

After thoroughly investigating this matter, it appears that implementing styled-components for server-side rendering in Next.js 13 with the app router is not feasible. However, there are workarounds to ensure styled-components function properly in Next.js 13 without encountering any "delay bugs" by utilizing client-side rendering.

To achieve this, follow these steps:

  1. Include the code snippet below in your next.config.js file:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  compiler: {
    styledComponents: true,
  },
}

module.exports = nextConfig

  1. Create a registry.tsx file containing the provided code:

'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
 
export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())
 
  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement()
    styledComponentsStyleSheet.instance.clearTag()
    return styles
  })
 
  if (typeof window !== 'undefined') return <>{children}</>
 
  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  )
}

3 - Insert the 'use client' directive into your layout.tsx file and wrap all the child components of your layout with the StyledComponentsRegistry component.

I have created a detailed tutorial video on Youtube addressing this issue, which elaborates on the workaround:

watch?v=3tgrPm2aKog

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a function in the view/template with Angular 2+

Whenever a function is called in the view of an Angular component, it seems to be executed repeatedly. A typical example of this scenario can be seen below: nightclub.component.ts import { Component } from '@angular/core'; @Component({ selec ...

What is the best way to create an instance method in a subclass that can also call a different instance method?

In our programming project, we have a hierarchy of classes where some classes inherit from a base class. Our goal is to create an instance method that is strongly-typed in such a way that it only accepts the name of another instance method as input. We d ...

Utilizing dynamic routes and incorporating additional search parameters within the URL structure in NextJS has never

Is there a way to use router.push(url); to redirect a user with a URL structure like this: [:lang]/something/[...dynamicRouteParams]?searchParam=true. The problem I'm facing is that the user ends up being redirected to a page with a URL structure lik ...

What is the preferred way to handle return values in a JQuery Ajax function - true or

Just a quick question about my AJAX function - should I include return statements in the code? Here's an example for reference: $.ajax({ type: 'POST', url: 'Application.cfc?method=runProcess', data: {'userID' ...

Exploring the possibility of detecting page scrolling in Javascript by clicking on scroll bars

I have implemented a unique feature on my page that allows users to scroll up and down using custom buttons I created. This functionality is achieved by smoothly transitioning between anchor points on the page using jQuery's animate function. However ...

What sets aws-cdk-lib apart from @aws-cdk/core, @aws-cdk/aws-iam, and others?

There seems to be a variety of examples out there using the AWS CDK, with some referencing aws-cdk-lib and others using @aws-cdk/core. Can someone clarify the distinction between these two and provide guidance on when to use one over the other? ...

Issue with Material-ui autocomplete not updating its displayed value according to the value prop

My task involved creating multiple rows, each containing a searchable Autocomplete dropdown populated through an API, along with other fields. Everything was functioning perfectly until I encountered an issue when deleting a row from the middle. After dele ...

The combination of Node.js module.exports and shorthand ternary operators for conditional statements

Can you explain the purpose of this line 'undefined' != typeof User ? User : module.exports and why is everything enclosed within (function(){})? I am having trouble understanding its significance. This code snippet is extracted from a library f ...

"Improprove your website's user experience by implementing Material UI Autocomplete with the

Recently, I experimented with the Autocomplete feature in Material UI. The focus was on adding an option when entering a new value. You can check out the demo by clicking on this link: https://codesandbox.io/s/material-demo-forked-lgeju?file=/demo.js One t ...

Having trouble with document.getElementById.innerHTML not displaying the correct content?

document.getElementById works in getting the element, but for some reason, the content disappears as soon as it is written in it. There are no errors on the console to indicate what's causing this behavior. I have been unable to identify the reason b ...

"execute loop in a strange and peculiar manner using JavaScript

Implement a loop to place markers on the map: for (i = 0; i <= 6; i++) { _coord = prj_markers[i]; alert(i); instance.set_marker(instance, provider, i, _coord, divBlock); } This code displays "0" in an alert once and executes instance.set_m ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

Is it possible to terminate an active server process triggered by an HTTP post request in Node.js prior to returning a response?

I developed an application where I utilized Ajax to make calls to a Node server. The issue is that even if the user navigates to another page, the server persists in processing the initial request made by the Ajax call. It then proceeds to process the new ...

JavaScript not functional, database being updated through AJAX calls

I have created a game using Phaser, a JavaScript library for games. Now I am looking to implement a score table using JS/PHP. My main focus is on transferring a variable from JS to PHP in order to update the database. I have researched numerous topics and ...

Preventing page refresh when typing in a form input: Tips and tricks

I'm currently puzzled by a small issue. In my web application, I have a chat box that consists of an input[type='text'] field and a button. My goal is to send the message to the server and clear the input field whenever the user clicks the b ...

Tips for swapping out a page for a component

Consider a scenario where we have a blog page containing a div element with the class "content" that displays previews of various articles. The goal is to dynamically replace the content within the div element with a specific article. How can this be acco ...

Accessing and fetching data from a PostgreSQL database using JavaScript through an API

I am currently working with an npm package called tcmb-doviz-kuru to fetch currency data from an API and then insert it into my database. However, I am facing an issue with mapping the data to properly insert the values. Below is my code snippet: var tcmbD ...

What steps should I take to ensure that elements beneath a div are made visible?

I've been working on a unique project to create a website with "hidden text" elements. One of the cool features I've developed is a circular div that follows my mouse cursor and flips all text below it using background-filter in both CSS and Jav ...

Ways to thwart CSRF attacks?

I am currently looking for ways to protect my API from CSRF attacks in my Express app using Node.js. Despite searching on both Google and YouTube, I have been unable to find a solution that works for me. One tutorial I watched on YouTube recommended gene ...

Eliminate duplicate objects from arrays of objects by a specific key name

Here are some arrays of objects I am working with: var arr = [ {name: 'john', last: 'smith'}, {name: 'jane', last: 'doe'}, {name: 'johnny', last: 'appleseed'}, {name: 'johnson', ...