Product
Introducing SSO
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
obj-serialize
Advanced tools
Readme
obj-serialize
is a library containing utility functions and building blocks in to serialize objects to be passed around to another context, between applications or between APIs.
but what does the library description mean...?
Let's take a Next.js for an example and let's assume you have some kind of service that queries your database and returns some data about dogs.
// services/get-dogs.js
const dogs = [
{
name: 'fafik',
size: 'small',
birth: new Date('1995-12-17T03:24:00'),
},
{
name: 'pimpek',
size: 'big',
birth: new Date('1995-12-17T03:24:00'),
},
]
export function getDogs(size) {
// In real world scenario, this probably will be a call to the database
return dogs.filter(({ size: dogSize }) => dogSize === size)
}
Then you want to execute this service and pass the data to your frontend application via getServerSideProps
// pages/index.js
import { getDogs } from 'services/get-dogs'
export async function getServerSideProps() {
const smallDogs = getDogs('small')
return {
props: {
smallDogs,
},
}
}
export default function Home({ smallDogs }) {
return <div>hello {smallDogs[0].name}</div>
}
Next.js won’t serialize Date
object that is present in the smallDogs
variable. It can only serialize JSON serializable data types.
The error when opening the home page would look like this:
[!CAUTION] Error: Error serializing
.smallDogs[0].birth
returned fromgetServerSideProps
in “/“.
Reason:object
(“[object Date]”) cannot be serialized as JSON. Please only return JSON serializable data types.
Here comes the obj-serialize
library. You can just do
import { nextServerSideSerialize } from 'obj-serialize'
and use it somewhere in your code in order to make any object viable for Next.js to pass around!
// pages/index.js
import { nextServerSideSerialize } from 'obj-serialize'
import { getDogs } from '../services/get-dogs'
export async function getServerSideProps() {
const smallDogs = getDogs('small')
return {
props: {
smallDogs: smallDogs.map((dog) => nextServerSideSerialize(dog)),
},
}
}
export default function Home({ smallDogs }) {
return <div>siema {smallDogs[0].name}</div>
}
This will work flawlessly ✅
Apart from providing out-of-the-box working utility for serialisation that takes place in Next.js applications, the obj-serialize
also provides option to create your own serializers.
All you have to do is to import base building block of the library (serialize
function) and use it as you want.
import { serialize } from 'obj-serialize'
The function accepts data to be serialized as a first parameter and serialization rules as the second parameter. The rules parameter is nothing else but function that is used to “walk” through the object, be executed for each occurrence and eventually convert unserialized data into proper one by returning it.
[!NOTE] ℹ️ There is a special value called
SkipSerialization
. It is a unique token that is intended to be used when serialisation traverse does not meet any condition in your serialisation rules and you just need to skip the process for particular case. It has to be this token and notnull
orundefined
since these two can also have impact on desired data after the serialization.
Let’s assume that you want to convert all Date
objects not toISOString()
(as nextServerSideSerialize does) but rather toLocaleString()
.
import { serialize, SkipSerialization } from 'obj-serialize'
export function customSerialize(data) {
return serialize(data, (unserializedData) => {
if (unserializedData instanceof Date) {
return unserializedData.toLocaleString()
} else {
return SkipSerialization
}
})
}
and thats all! Now you can use your own serializer in the same way as presented here
The project is licensed under the MIT License. All contributions are welcome
FAQs
Simple utility to serialize objects to be passed around to another context. Useful in Next.js Pages Router projects.
The npm package obj-serialize receives a total of 1 weekly downloads. As such, obj-serialize popularity was classified as not popular.
We found that obj-serialize demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.