npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

pws-react-form-submission

v1.2.0

Published

React helper for CSRF + secure form submission

Readme

React Form Submission

Ready-to-use React utilities for CSRF + secure form submission.

Install

npm install pws-react-form-submission

Usage

import { useMemo, useState } from "react";
import {
  computePayloadHash,
  useFormSubmission,
  type FormClientConfig,
} from "pws-react-form-submission";

type SimpleForm = {
  name: string;
  email: string;
  amount: string;
  note: string;
};

export default function App() {
  const [baseUrl, setBaseUrl] = useState(
    "https://pwsdevenvironment.azure-api.net"
  );
  const [csrfPath, setCsrfPath] = useState(
    "/api/FormSubmissionService/forms/csrf/token"
  );
  const [submitPath, setSubmitPath] = useState(
    "/api/FormSubmissionService/forms/submit"
  );
  const [formCode, setFormCode] = useState("CreditCard");
  const [channel, setChannel] = useState("Aem_Form");
  const [subscriptionKey, setSubscriptionKey] = useState(
    "9a344a9ecef04eee8b59d78a579d1d50"
  );
  const [localError, setLocalError] = useState<string | null>(null);
  const [formData, setFormData] = useState<SimpleForm>({
    name: "",
    email: "",
    amount: "",
    note: "",
  });

  const clientConfig: FormClientConfig = useMemo(() => {
    const headers: Record<string, string> = {};
    if (subscriptionKey) {
      headers["Ocp-Apim-Subscription-Key"] = subscriptionKey;
    }
    return {
      baseUrl,
      csrfPath,
      submitPath,
      subscriptionKey,
      headers,
    };
  }, [baseUrl, csrfPath, submitPath, subscriptionKey]);

  const {
    fetchCsrf,
    submit,
    csrfStatus,
    csrfToken,
    loading,
    lastResponse,
    error,
  } = useFormSubmission(clientConfig);

  async function handleSave() {
    setLocalError(null);
    try {
      if (!subscriptionKey.trim()) {
        setLocalError("Ocp-Apim-Subscription-Key is required");
        return;
      }
      let tokenToUse = csrfToken;
      if (!tokenToUse) {
        const result = await fetchCsrf();
        tokenToUse = result.token;
      }
      const payload = {
        name: formData.name,
        email: formData.email,
        amount: formData.amount,
        note: formData.note,
      };
      const bodyForHash = {
        formCode,
        channel,
        payload,
      };
      const bodyString = JSON.stringify(bodyForHash);
      const headers: Record<string, string> = {};
      headers["X-Payload-Hash"] = await computePayloadHash(bodyString, "SHA-256");
      await submit({
        bodyString,
        headers,
        csrfToken: tokenToUse,
      });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setLocalError(message);
    }
  }

  return (
    <div className="app">
      <header className="hero">
        <div>
          <p className="eyebrow">Demo Form</p>
          <h1>React Form Save (CSRF → Save)</h1>
          <p className="sub">
            กด Save ระบบจะเรียก CSRF ก่อน แล้วส่งข้อมูลตามรูปแบบ FormCode/Channel
          </p>
        </div>
        <div className={`status-pill status-${csrfStatus}`}>
          CSRF: {csrfStatus}
        </div>
      </header>

      <div className="grid">
        <section className="card">
          <h2>Config</h2>
          <label>
            Base URL
            <input
              value={baseUrl}
              onChange={(e) => setBaseUrl(e.target.value)}
              placeholder="https://pwsdevenvironment.azure-api.net"
            />
          </label>
          <label>
            CSRF Path
            <input
              value={csrfPath}
              onChange={(e) => setCsrfPath(e.target.value)}
              placeholder="/api/FormSubmissionService/forms/csrf/token"
            />
          </label>
          <label>
            Submit Path
            <input
              value={submitPath}
              onChange={(e) => setSubmitPath(e.target.value)}
              placeholder="/api/FormSubmissionService/forms/submit"
            />
          </label>
          <label>
            APIM Subscription Key
            <input
              value={subscriptionKey}
              onChange={(e) => setSubscriptionKey(e.target.value)}
              placeholder="9a344a9ecef04eee8b59d78a579d1d50"
            />
          </label>
        </section>

        <section className="card">
          <h2>Form</h2>
          <label>
            FormCode
            <input
              value={formCode}
              onChange={(e) => setFormCode(e.target.value)}
            />
          </label>
          <label>
            Channel
            <input
              value={channel}
              onChange={(e) => setChannel(e.target.value)}
            />
          </label>
          <label>
            Name
            <input
              value={formData.name}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, name: e.target.value }))
              }
              placeholder="John Doe"
            />
          </label>
          <label>
            Email
            <input
              value={formData.email}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, email: e.target.value }))
              }
              placeholder="[email protected]"
            />
          </label>
          <label>
            Amount
            <input
              value={formData.amount}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, amount: e.target.value }))
              }
              placeholder="1000"
            />
          </label>
          <label>
            Note
            <textarea
              rows={4}
              value={formData.note}
              onChange={(e) =>
                setFormData((prev) => ({ ...prev, note: e.target.value }))
              }
              placeholder="Additional info"
            />
          </label>
          <button
            type="button"
            className="btn primary"
            onClick={handleSave}
            disabled={loading}
          >
            {loading ? "Saving..." : "Save"}
          </button>
          {localError || error ? (
            <div className="error">{localError ?? error?.message}</div>
          ) : null}
        </section>
      </div>

      <section className="card response-card">
        <h2>Response</h2>
        <pre>
          {lastResponse
            ? JSON.stringify(lastResponse, null, 2)
            : "(no response yet)"}
        </pre>
      </section>
    </div>
  );
}

Notes

  • Provide baseUrl, csrfPath, and submitPath for your environment.
  • Supply Ocp-Apim-Subscription-Key when required by your API gateway.
  • computePayloadHash should match the hashing algorithm your backend expects.