blitz-js / next-superjson-plugin

SuperJSON Plugin for Next.js Pages and Components
192 stars 13 forks source link

SWC plugin doesn't deserialise props, however serialisation works fine #73

Closed shirshendubhowmick closed 1 year ago

shirshendubhowmick commented 1 year ago

Verify Next.js canary release

Describe the bug

The plugin auto serialised props while returning from getServerSideProps, this works as expected.

return {
  props: {
    dataToBeSerialized,
  },
}

However in side of the component prop, it's not deserialising the props. The date fields are still in string inside the component.

Expected behavior

As per the doc it should auto deserialise as well, so will expect the date date fields to be Date instead of string

Reproduction link

No response

Version

SWC plugin: 0.5.6 SuperJSON: 1.12.2

Config

const nextConfig = {
  pageExtensions: ["ts", "tsx", "js", "jsx", "md", "mdx"],
  experimental: {
    swcPlugins: [["next-superjson-plugin", {}]],
  },
};

Additional context

I have tested it in Next latest stable and canary version

orionmiz commented 1 year ago

Please provide more detailed explanation to reproduce this bug.

shirshendubhowmick commented 1 year ago

@orionmiz While I was creating a repo to reproduce this issue, I noticed an additional detail which might be helpful.

The deserialisation works fine when the component and getServerSideProps are on the same TS file and it doesn't work when they are on a different file.

This is a repo you can check: https://github.com/shirshendubhowmick/superjson-swc-plugin-bug

http://localhost:8090/demo1 http://localhost:8090/demo2

For the case of demo1 you will notice that in your console it prints the type of the date as string (deserialisation not working).

For demo2 you will notice that in your console it prints the type of the date as object (deserialisation works fine here).

So this issue occurs when getServerSideProps is defined on a different file WRT to the component.

shirshendubhowmick commented 1 year ago

@orionmiz For the time being any workaround you can suggest ?

orionmiz commented 1 year ago

This is a similar issue with https://github.com/blitz-js/next-superjson-plugin/issues/1#issuecomment-1206776969

next-superjson-plugin assumes that the page component from any external sources like ../views/Demo/Demo is already wrapped with SuperJSON deserializer and skips the wrapping for optimization purposes.

This is the intended behavior, so always place your page component inside the pages directory if possible.

Here's a workaround using plugin API directly:

import { withSuperJSONPage } from "next-superjson-plugin/tools";
import DemoView from "../views/Demo/Demo";
export default withSuperJSONPage(DemoView)