Next.js Discord

Discord Forum

How to sanitise and validate JSON input

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
I'm trying to make a import/export feature of the user's localdata using JSON. I have no idea about JSON, so I need help in making a validation and sanitise feature.

Local data contains multiple Tab elements, defined as follows:
type Product = {
  imageURL: string;
  productBrand: string;
  productCategory: number;
  productId: number;
  productName: string;
  productPrice: number;
  shopImageURL: string;
  shopName: string;
  shopURL: string;
};

type Tab = {
  id: number;
  name: string;
  term: string;
  products: Product[];
  seenItems: Set<number>;
  newItems: Product[];
};

This is how the import and export are written:
const handleImportData = (data: string) => {

    try {
      const parsedData = JSON.parse(decodeURIComponent(data));



      const importedTabs: Tab[] = parsedData.map((tab: any) => ({
        ...tab,
        seenItems: new Set(tab.seenItems),
      }));

      setTabs(importedTabs);
      if (importedTabs.length > 0) {
        setActiveTabId(importedTabs[0].id);
      }
    } catch (err) {
      console.error("Error parsing imported tabs data:", err);
      // Handle error state or show error message
    }
  };

const handleExportData = () => {
    const tabsData = tabs.map((tab) => ({
      ...tab,
      seenItems: Array.from(tab.seenItems),
    }));

    const dataStr = encodeURIComponent(JSON.stringify(tabsData));
    return dataStr;
  };

  const handleResetData = () => {
    setTabs([]);
    setActiveTabId(null);
  };
|

any help would be appreciated.

2 Replies

Horned oak gall
you could use someting like zod for validation: https://zod.dev/
import { z } from "zod";

export const ContactValidators = z.object({
  email: z.string().email({
    message: "I haven't figured that kinda email",
  }),
  isNewsLetter: z.enum(["true", "false"]).default("true"),
  description: z
    .string()
    .min(25, {
      message: "Hey! atleast take a effort! for 25 char :)",
    })
    .max(1000, {
      message: "dude! Well explained but its too long!",
    }),
  firstName: z
    .string()
    .min(3, {
      message: "Your name that short ?",
    })
    .max(15, {
      message: "Maybe shorten a bit, Soo i can spell it :)",
    }),
  lastName: z
    .string()
    .min(2, {
      message: "Too short to be a name dude!",
    })
    .max(15, {
      message: "Maybe shorten a bit, Soo i can spell it :)",
    }),
});

export type TContactValidators = z.infer<typeof ContactValidators>;


 const body = await request.json();
// could do a safeparse or parse which will throw error.
 const { lastName, firstName } = ContactValidators.parse(body);