Gathering detailed insights and metrics for @designerstrust/remix-utils
Gathering detailed insights and metrics for @designerstrust/remix-utils
Gathering detailed insights and metrics for @designerstrust/remix-utils
Gathering detailed insights and metrics for @designerstrust/remix-utils
A set of utility functions and types to use with Remix.run
npm install @designerstrust/remix-utils
Typescript
Module System
Min. Node Version
Node Version
NPM Version
64.2
Supply Chain
91.4
Quality
74.8
Maintenance
50
Vulnerability
99.6
License
TypeScript (100%)
Total Downloads
957
Last Day
1
Last Week
8
Last Month
23
Last Year
564
MIT License
2,314 Stars
395 Commits
139 Forks
10 Watchers
4 Branches
64 Contributors
Updated on Jun 30, 2025
Minified
Minified + Gzipped
Latest Version
5.2.0
Package Id
@designerstrust/remix-utils@5.2.0
Unpacked Size
212.49 kB
Size
38.22 kB
File Count
131
NPM Version
8.19.2
Node Version
16.18.1
Cumulative downloads
Total Downloads
Last Day
0%
1
Compared to previous day
Last Week
0%
8
Compared to previous week
Last Month
-78.9%
23
Compared to previous month
Last Year
91.8%
564
Compared to previous year
4
38
This package contains simple utility functions to use with Remix.run.
1npm install remix-utils
The promiseHash
function is not directly related to Remix but it's a useful function when working with loaders and actions.
This function is an object version of Promise.all
which lets you pass an object with promises and get an object with the same keys with the resolved values.
1export let loader: LoaderFunction = async ({ request }) => { 2 return json( 3 promiseHash({ 4 user: getUser(request), 5 posts: getPosts(request), 6 }) 7 ); 8};
You can use nested promiseHash
to get a nested object with resolved values.
1export let loader: LoaderFunction = async ({ request }) => {
2 return json(
3 promiseHash({
4 user: getUser(request),
5 posts: promiseHash({
6 list: getPosts(request),
7 comments: promiseHash({
8 list: getComments(request),
9 likes: getLikes(request),
10 }),
11 }),
12 })
13 );
14};
Note This can only be run inside
entry.client
.
This function lets you easily cache inside the browser's Cache Storage every JS file built by Remix.
To use it, open your entry.client
file and add this:
1import { cacheAssets } from "remix-utils"; 2 3cacheAssets().catch((error) => { 4 // do something with the error, or not 5});
The function receives an optional options object with two options:
cacheName
is the name of the Cache object to use, the default value is assets
.buildPath
is the pathname prefix for all Remix built assets, the default value is /build/
which is the default build path of Remix itself.It's important that if you changed your build path in remix.config.js
you pass the same value to cacheAssets
or it will not find your JS files.
The cacheName
can be left as is unless you're adding a Service Worker to your app and want to share the cache.
1cacheAssests({ cacheName: "assets", buildPath: "/build/" }).catch((error) => { 2 // do something with the error, or not 3});
The ClientOnly component lets you render the children element only on the client-side, avoiding rendering it the server-side.
You can provide a fallback component to be used on SSR, and while optional, it's highly recommended to provide one to avoid content layout shift issues.
1import { ClientOnly } from "remix-utils"; 2 3export default function View() { 4 return ( 5 <ClientOnly fallback={<SimplerStaticVersion />}> 6 {() => <ComplexComponentNeedingBrowserEnvironment />} 7 </ClientOnly> 8 ); 9}
This component is handy when you have some complex component that needs a browser environment to work, like a chart or a map. This way, you can avoid rendering it server-side and instead use a simpler static version like an SVG or even a loading UI.
The rendering flow will be:
This component uses the useHydrated
hook internally.
The CORS function let you implement CORS headers on your loaders and actions so you can use them as an API for other client-side applications.
There are two main ways to use the cors
function.
If you want to use it on every loader/action, you can do it like this:
1export let loader: LoaderFunction = async ({ request }) => { 2 let data = await getData(request); 3 let response = json<LoaderData>(data); 4 return await cors(request, response); 5};
You could also do the json
and cors
call in one line.
1export let loader: LoaderFunction = async ({ request }) => { 2 let data = await getData(request); 3 return await cors(request, json<LoaderData>(data)); 4};
And because cors
mutates the response, you can also call it and later return.
1export let loader: LoaderFunction = async ({ request }) => { 2 let data = await getData(request); 3 let response = json<LoaderData>(data); 4 await cors(request, response); // this mutates the Response object 5 return response; // so you can return it here 6};
If you want to setup it globally once, you can do it like this in entry.server
1export let handleDataRequest: HandleDataRequestFunction = async ( 2 response, 3 { request } 4) => { 5 return await cors(request, response); 6};
Additionally, the cors
function accepts a options
object as a third optional argument. These are the options.
origin
: Configures the Access-Control-Allow-Origin CORS header.
Possible values are:
true
: Enable CORS for any origin (same as "*")false
: Don't setup CORSstring
: Set to a specific origin, if set to "*" it will allow any originRegExp
: Set to a RegExp to match against the originArray<string | RegExp>
: Set to an array of origins to match against the
string or RegExpFunction
: Set to a function that will be called with the request origin
and should return a boolean indicating if the origin is allowed or not.
The default value is true
.methods
: Configures the Access-Control-Allow-Methods CORS header.
The default value is ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"]
.allowedHeaders
: Configures the Access-Control-Allow-Headers CORS header.exposedHeaders
: Configures the Access-Control-Expose-Headers CORS header.credentials
: Configures the Access-Control-Allow-Credentials CORS header.maxAge
: Configures the Access-Control-Max-Age CORS header.The CSRF related functions let you implement CSRF protection on your application.
This part of Remix Utils needs React and server-side code.
In the server, we need to add to our root
component the following.
1import type { LoaderFunction } from "remix"; 2import { createAuthenticityToken, json } from "remix-utils"; 3import { getSession, commitSession } from "~/services/session.server"; 4 5interface LoaderData { 6 csrf: string; 7} 8 9export let loader: LoaderFunction = async ({ request }) => { 10 let session = await getSession(request.headers.get("cookie")); 11 let token = createAuthenticityToken(session); 12 return json<LoaderData>( 13 { csrf: token }, 14 { headers: { "Set-Cookie": await commitSession(session) } } 15 ); 16};
The createAuthenticityToken
function receives a session object and stores the authenticity token there using the csrf
key (you can pass the key name as a second argument). Finally, you need to return the token in a json
response and commit the session.
You need to read the authenticity token and render the AuthenticityTokenProvider
component wrapping your code in your root.
1import { Outlet, useLoaderData } from "remix"; 2import { Document } from "~/components/document"; 3 4export default function Root() { 5 let { csrf } = useLoaderData<LoaderData>(); 6 return ( 7 <AuthenticityTokenProvider token={csrf}> 8 <Document> 9 <Outlet /> 10 </Document> 11 </AuthenticityTokenProvider> 12 ); 13}
With this, your whole app can access the authenticity token generated in the root.
When you create a form in some route, you can use the AuthenticityTokenInput
component to add the authenticity token to the form.
1import { Form } from "remix"; 2import { AuthenticityTokenInput } from "remix-utils"; 3 4export default function SomeRoute() { 5 return ( 6 <Form method="post"> 7 <AuthenticityTokenInput /> 8 <input type="text" name="something" /> 9 </Form> 10 ); 11}
Note that the authenticity token is only really needed for a form that mutates the data somehow. If you have a search form making a GET request, you don't need to add the authenticity token there.
This AuthenticityTokenInput
will get the authenticity token from the AuthenticityTokenProvider
component and add it to the form as the value of a hidden input with the name csrf
. You can customize the field name using the name
prop.
1<AuthenticityTokenInput name="customName" />
You should only customize the name if you also changed it on createAuthenticityToken
.
useAuthenticityToken
and useFetcher
.If you need to use useFetcher
(or useSubmit
) instead of Form
you can also get the authenticity token with the useAuthenticityToken
hook.
1import { useFetcher } from "remix"; 2import { useAuthenticityToken } from "remix-utils"; 3 4export function useMarkAsRead() { 5 let fetcher = useFetcher(); 6 let csrf = useAuthenticityToken(); 7 return function submit(data) { 8 fetcher.submit({ csrf, ...data }, { action: "/action", method: "post" }); 9 }; 10}
Finally, you need to verify the authenticity token in the action that received the request.
1import type { ActionFunction } from "remix";
2import { verifyAuthenticityToken, redirectBack } from "remix-utils";
3import { getSession, commitSession } from "~/services/session.server";
4
5export let action: ActionFunction = async ({ request }) => {
6 let session = await getSession(request.headers.get("Cookie"));
7 await verifyAuthenticityToken(request, session);
8 // do something here
9 return redirectBack(request, { fallback: "/fallback" });
10};
Suppose the authenticity token is missing on the session, the request body, or doesn't match. In that case, the function will throw an Unprocessable Entity response that you can either catch and handle manually or let pass and render your CatchBoundary.
If you need to create <link />
tags based on the loader data instead of being static, you can use the DynamicLinks
component together with the DynamicLinksFunction
type.
In the route you want to define dynamic links add handle
export with a dynamicLinks
method, this method should implement the DynamicLinksFunction
type.
1// create the dynamicLinks function with the correct type 2// note: loader type is optional 3let dynamicLinks: DynamicLinksFunction<SerializeFrom<typeof loader>> = ({ 4 id, 5 data, 6 params, 7 location, 8 parentsData, 9}) => { 10 if (!data.user) return []; 11 return [{ rel: "preload", href: data.user.avatar, as: "image" }]; 12}; 13 14// and export it through the handle, you could also create it inline here 15// if you don't care about the type 16export let handle = { dynamicLinks };
Then, in the root route, add the DynamicLinks
component before the Remix's Links component, usually inside a Document component.
1import { Links, LiveReload, Meta, Scripts, ScrollRestoration } from "remix"; 2import { DynamicLinks } from "remix-utils"; 3 4type Props = { children: React.ReactNode; title?: string }; 5 6export function Document({ children, title }: Props) { 7 return ( 8 <html lang="en"> 9 <head> 10 <meta charSet="utf-8" /> 11 <meta name="viewport" content="width=device-width,initial-scale=1" /> 12 {title ? <title>{title}</title> : null} 13 <Meta /> 14 <DynamicLinks /> 15 <Links /> 16 </head> 17 <body> 18 {children} 19 <ScrollRestoration /> 20 <Scripts /> 21 <LiveReload /> 22 </body> 23 </html> 24 ); 25}
Now, any link you defined in the DynamicLinksFunction
will be added to the HTML as any static link in your LinksFunction
s.
Note You can also put the
DynamicLinks
after theLinks
component, it's up to you what to prioritize, since static links are probably prefetched when you do<Link prefetch>
you may want to put theDynamicLinks
first to prioritize them.
If you need to load different external scripts on certain routes, you can use the ExternalScripts
component together with the ExternalScriptsFunction
type.
In the route you want to load the script add a handle
export with a scripts
method, this method should implement the ExternalScriptsFunction
type.
1// create the scripts function with the correct type 2// note: loader type is optional 3let scripts: ExternalScriptsFunction<SerializeFrom<typeof loader>> = ({ 4 id, 5 data, 6 params, 7 location, 8 parentsData, 9}) => { 10 return [ 11 { 12 src: "https://code.jquery.com/jquery-3.6.0.min.js", 13 integrity: "sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=", 14 crossOrigin: "anonymous", 15 }, 16 ]; 17}; 18 19// and export it through the handle, you could also create it inline here 20// if you don't care about the type 21export let handle = { scripts };
Then, in the root route, add the ExternalScripts
component together with the Remix's Scripts component, usually inside a Document component.
1import { Links, LiveReload, Meta, Scripts, ScrollRestoration } from "remix"; 2import { ExternalScripts } from "remix-utils"; 3 4type Props = { children: React.ReactNode; title?: string }; 5 6export function Document({ children, title }: Props) { 7 return ( 8 <html lang="en"> 9 <head> 10 <meta charSet="utf-8" /> 11 <meta name="viewport" content="width=device-width,initial-scale=1" /> 12 {title ? <title>{title}</title> : null} 13 <Meta /> 14 <Links /> 15 </head> 16 <body> 17 {children} 18 <ScrollRestoration /> 19 <ExternalScripts /> 20 <Scripts /> 21 <LiveReload /> 22 </body> 23 </html> 24 ); 25}
Now, any script you defined in the ScriptsFunction will be added to the HTML together with a <link rel="preload">
before it.
Tip: You could use it together with useShouldHydrate to disable Remix scripts in certain routes but still load scripts for analytics or small features that need JS but don't need the full app JS to be enabled.
If you need to include structured data (JSON-LD) scripts on certain routes, you can use the StructuredData
component together with the HandleStructuredData
type or StructuredDataFunction
type.
In the route you want to include the structured data, add a handle
export with a structuredData
method, this method should implement the StructuredDataFunction
type.
1import type { WithContext, BlogPosting } from "schema-dts"; 2 3// create the structuredData function with the correct type 4// note: loader type is optional 5let structuredData: StructuredDataFunction< 6 SerializeFrom<typeof loader>, 7 BlogPosting 8> = ({ id, data, params, location, parentsData }) => { 9 let { post } = data; 10 11 return { 12 "@context": "https://schema.org", 13 "@type": "BlogPosting", 14 datePublished: post.published, 15 mainEntityOfPage: { 16 "@type": "WebPage", 17 "@id": post.postUrl, 18 }, 19 image: post.featuredImage, 20 author: { 21 "@type": "Person", 22 name: post.authorName, 23 }, 24 }; 25}; 26 27// and export it through the handle, you could also create it inline here 28// if you don't care about the type or using the `HandleStructuredData` type 29export let handle = { structuredData };
Then, in the root route, add the StructuredData
component together with the Remix's Scripts component, usually inside a Document component.
1import { Links, LiveReload, Meta, Scripts, ScrollRestoration } from "remix"; 2import { StructuredData } from "remix-utils"; 3 4type Props = { children: React.ReactNode; title?: string }; 5 6export function Document({ children, title }: Props) { 7 return ( 8 <html lang="en"> 9 <head> 10 <meta charSet="utf-8" /> 11 <meta name="viewport" content="width=device-width,initial-scale=1" /> 12 {title ? <title>{title}</title> : null} 13 <Meta /> 14 <Links /> 15 <StructuredData /> 16 </head> 17 <body> 18 {children} 19 <ScrollRestoration /> 20 <Scripts /> 21 <LiveReload /> 22 </body> 23 </html> 24 ); 25}
Now, any structured data you defined in the StructuredDataFunction
will be added to the HTML, in the head. You may choose to include the <StructuredData />
in either the head or the body, both are valid.
This hook lets you trigger a refresh of the loaders in the current URL.
The way this works is by sending a fetcher.submit to /dev/null
to trigger all loaders to run.
You need to create app/routes/dev/null.ts
and define an action that returns null.
1// app/routes/dev/null.ts 2export function action() { 3 return null; 4}
This Hook is mostly useful if you want to trigger the refresh manually from an effect, examples of this are:
1import { useDataRefresh } from "remix-utils"; 2 3function useDataRefreshOnInterval() { 4 let { refresh } = useDataRefresh(); 5 useEffect(() => { 6 let interval = setInterval(refresh, 5000); 7 return () => clearInterval(interval); 8 }, [refresh]); 9}
The return value of useDataRefresh
is an object with the following keys:
init
, refreshRedirect
or refresh
loading
or idle
This hook lets you know if the value of transition.state
and every fetcher.state
in the app.
1import { useGlobalTransitionStates } from "remix-utils"; 2 3export function GlobalPendingUI() { 4 let states = useGlobalTransitionStates(); 5 6 if (state.includes("loading")) { 7 // The app is loading. 8 } 9 10 if (state.includes("submitting")) { 11 // The app is submitting. 12 } 13 14 // The app is idle 15}
The return value of useGlobalTransitionStates
can be "idle"
, "loading"
or "submitting"
Note This is used by the hooks below to determine if the app is loading, submitting or both (pending).
This hook lets you know if the global transition or if one of any active fetchers is either loading or submitting.
1import { useGlobalPendingState } from "remix-utils"; 2 3export function GlobalPendingUI() { 4 let globalState = useGlobalPendingState(); 5 6 if (globalState === "idle") return null; 7 return <Spinner />; 8}
The return value of useGlobalPendingState
is either "idle"
or "pending"
.
Note: This hook combines the
useGlobalSubmittingState
anduseGlobalLoadingState
hooks to determine if the app is pending.
Note: The
pending
state is a combination of theloading
andsubmitting
states introduced by this hook.
This hook lets you know if the global transition or if one of any active fetchers is submitting.
1import { useGlobalSubmittingState } from "remix-utils"; 2 3export function GlobalPendingUI() { 4 let globalState = useGlobalSubmittingState(); 5 6 if (globalState === "idle") return null; 7 return <Spinner />; 8}
The return value of useGlobalSubmittingState
is either "idle"
or "submitting"
.
This hook lets you know if the global transition or if one of any active fetchers is loading.
1import { useGlobalLoadingState } from "remix-utils"; 2 3export function GlobalPendingUI() { 4 let globalState = useGlobalLoadingState(); 5 6 if (globalState === "idle") return null; 7 return <Spinner />; 8}
The return value of useGlobalLoadingState
is either "idle"
or "loading"
.
This hook lets you detect if your component is already hydrated. This means the JS for the element loaded client-side and React is running.
With useHydrated, you can render different things on the server and client while ensuring the hydration will not have a mismatched HTML.
1import { useHydrated } from "remix-utils"; 2 3export function Component() { 4 let isHydrated = useHydrated(); 5 6 if (isHydrated) { 7 return <ClientOnlyComponent />; 8 } 9 10 return <ServerFallback />; 11}
When doing SSR, the value of isHydrated
will always be false
. The first client-side render isHydrated
will still be false, and then it will change to true
.
After the first client-side render, future components rendered calling this hook will receive true
as the value of isHydrated
. This way, your server fallback UI will never be rendered on a route transition.
This hooks lets you get the locales returned by the root loader. It follows a simple convention, your root loader return value should be an objet with the key locales
.
You can combine it with getClientLocal
to get the locales on the root loader and return that. The return value of useLocales
is a Locales
type which is string | string[] | undefined
.
1// in the root loader 2export let loader: LoaderFunction = async ({ request }) => { 3 let locales = getClientLocales(request); 4 return json({ locales }); 5}; 6 7// in any route (including root!) 8export default function Screen() { 9 let locales = useLocales(); 10 let date = new Date(); 11 let dateTime = date.toISOString; 12 let formattedDate = date.toLocaleDateString(locales, options); 13 return <time dateTime={dateTime}>{formattedDate}</time>; 14}
The return type of useLocales
is ready to be used with the Intl API.
This hook lets you access the data of any route in the current page. This can include child or parent routes.
To use it, call useRouteData
in your component and pass the route ID as a string. As an example, if you had the following routes:
routes/articles/$slug.tsx
routes/articles/index.tsx
routes/articles.tsx
Then you need to pass useRouteData("routes/articles")
to get the data of routes/articles.tsx
, useRouteData("routes/articles/index")
to get the data of routes/articles/index.tsx
and routes/articles/$slug
to get the data of routes/articles/$slug.tsx
.
As you can see, the ID is the route file without the extension.
1let parentData = useRouteData("routes/articles"); 2let indexData = useRouteData("routes/articles/index");
The useRouteData
hook receives a generic to be used as the type of the route data. Because the route may not be found the return type is Data | undefined
. This means if you do the following:
1let data = useRouteData<ArticleShowData>("routes/articles");
The type of data
will be ArticleShowData | undefined
, so you will need to check if it's not undefined before being able to use it.
If you are building a Remix application where most routes are static, and you want to avoid loading client-side JS, you can use this hook, plus some conventions, to detect if one or more active routes needs JS and only render the Scripts component in that case.
In your document component, you can call this hook to dynamically render the Scripts component if needed.
1import type { ReactNode } from "react"; 2import { Links, LiveReload, Meta, Scripts } from "remix"; 3import { useShouldHydrate } from "remix-utils"; 4 5interface DocumentProps { 6 children: ReactNode; 7 title?: string; 8} 9 10export function Document({ children, title }: DocumentProps) { 11 let shouldHydrate = useShouldHydrate(); 12 return ( 13 <html lang="en"> 14 <head> 15 <meta charSet="utf-8" /> 16 <link rel="icon" href="/favicon.png" type="image/png" /> 17 {title ? <title>{title}</title> : null} 18 <Meta /> 19 <Links /> 20 </head> 21 <body> 22 {children} 23 {shouldHydrate && <Scripts />} 24 <LiveReload /> 25 </body> 26 </html> 27 ); 28}
Now, you can export a handle
object with the hydrate
property as true
in any route module.
1export let handle = { hydrate: true };
This will mark the route as requiring JS hydration.
In some cases, a route may need JS based on the data the loader returned. For example, if you have a component to purchase a product, but only authenticated users can see it, you don't need JS until the user is authenticated. In that case, you can make hydrate
be a function receiving your loader data.
1export let handle = { 2 hydrate(data: LoaderData) { 3 return data.user.isAuthenticated; 4 }, 5};
The useShouldHydrate
hook will detect hydrate
as a function and call it using the route data.
This function receives a Request or Headers objects and will try to get the IP address of the client (the user) who originated the request.
1export let loader: LoaderFunction = async ({ request }) => {
2 // using the request
3 let ipAddress = getClientIPAddress(request);
4 // or using the headers
5 let ipAddress = getClientIPAddress(request.headers);
6};
If it can't find he ipAddress the return value will be null
. Remember to check if it was able to find it before using it.
The function uses the following list of headers, in order of preference:
When a header is found that contains a valid IP address, it will return without checking the other headers.
This function let you get the locales of the client (the user) who originated the request.
1export let loader: LoaderFunction = async ({ request }) => {
2 // using the request
3 let locales = getClientLocales(request);
4 // or using the headers
5 let locales = getClientLocales(request.headers);
6};
The return value is a Locales type, which is string | string[] | undefined
.
The returned locales can be directly used on the Intl API when formatting dates, numbers, etc.
1import { getClientLocales } from "remix-utils";
2export let loader: LoaderFunction = async ({ request }) => {
3 let locales = getClientLocales(request);
4 let nowDate = new Date();
5 let formatter = new Intl.DateTimeFormat(locales, {
6 year: "numeric",
7 month: "long",
8 day: "numeric",
9 });
10 return json({ now: formatter.format(nowDate) });
11};
The value could also be returned by the loader and used on the UI to ensure the user's locales is used on both server and client formatted dates.
This function let you identify if a request was created because of a prefetch triggered by using <Link prefetch="intent">
or <Link prefetch="render">
.
This will let you implement a short cache only for prefetch requests so you avoid the double data request.
1export let loader: LoaderFunction = async ({ request }) => { 2 let data = await getData(request); 3 let headers = new Headers(); 4 5 if (isPrefetch(request)) { 6 headers.set("Cache-Control", "private, max-age=5, smax-age=0"); 7 } 8 9 return json(data, { headers }); 10};
This function is a wrapper of the redirect
helper from Remix. Unlike Remix's version, this one receives the whole request object as the first value and an object with the response init and a fallback URL.
The response created with this function will have the Location
header pointing to the Referer
header from the request, or if not available, the fallback URL provided in the second argument.
1import { redirectBack } from "remix-utils"; 2import type { ActionFunction } from "remix"; 3 4export let action: ActionFunction = async ({ request }) => { 5 await redirectBack(request, { fallback: "/" }); 6};
This helper is most useful when used in a generic action to send the user to the same URL it was before.
Helper function to create a Created (201) response with a JSON body.
1import { created } from "remix-utils"; 2import type { ActionFunction } from "remix"; 3 4export let action: ActionFunction = async ({ request }) => { 5 let result = await doSomething(request); 6 return created(result); 7};
Helper function to create a Bad Request (400) response with a JSON body.
1import { badRequest } from "remix-utils"; 2import type { ActionFunction } from "remix"; 3 4export let action: ActionFunction = async () => { 5 throw badRequest({ message: "You forgot something in the form." }); 6};
Helper function to create an Unauthorized (401) response with a JSON body.
1import { unauthorized } from "remix-utils"; 2import type { LoaderFunction } from "remix"; 3 4export let loader: LoaderFunction = async () => { 5 // usually what you really want is to throw a redirect to the login page 6 throw unauthorized({ message: "You need to login." }); 7};
Helper function to create a Forbidden (403) response with a JSON body.
1import { forbidden } from "remix-utils"; 2import type { LoaderFunction } from "remix"; 3 4export let loader: LoaderFunction = async () => { 5 throw forbidden({ message: "You don't have access for this." }); 6};
Helper function to create a Not Found (404) response with a JSON body.
1import { notFound } from "remix-utils"; 2import type { LoaderFunction } from "remix"; 3 4export let loader: LoaderFunction = async () => { 5 throw notFound({ message: "This doesn't exists." }); 6};
Helper function to create an Unprocessable Entity (422) response with a JSON body.
1import { unprocessableEntity } from "remix-utils"; 2import type { LoaderFunction } from "remix"; 3 4export let loader: LoaderFunction = async () => { 5 throw unprocessableEntity({ message: "This doesn't exists." }); 6};
This is used by the CSRF validation. You probably don't want to use it directly.
Helper function to create a Server Error (500) response with a JSON body.
1import { serverError } from "remix-utils"; 2import type { LoaderFunction } from "remix"; 3 4export let loader: LoaderFunction = async () => { 5 throw serverError({ message: "Something unexpected happened." }); 6};
Helper function to create a Not Modified (304) response without a body and any header.
1export let loader: LoaderFunction = async ({ request }) => { 2 return notModified(); 3};
Helper function to create a JavaScript file response with any header.
This is useful to create JS files based on data inside a Resource Route.
1export let loader: LoaderFunction = async ({ request }) => { 2 return javascript("console.log('Hello World')"); 3};
Helper function to create a CSS file response with any header.
This is useful to create CSS files based on data inside a Resource Route.
1export let loader: LoaderFunction = async ({ request }) => { 2 return stylesheet("body { color: red; }"); 3};
Helper function to create a PDF file response with any header.
This is useful to create PDF files based on data inside a Resource Route.
1export let loader: LoaderFunction = async ({ request }) => { 2 return pdf(await generatePDF(request.formData())); 3};
Helper function to create a HTML file response with any header.
This is useful to create HTML files based on data inside a Resource Route.
1export let loader: LoaderFunction = async ({ request }) => { 2 return html("<h1>Hello World</h1>"); 3};
Cookie objects in Remix allows any type, the typed cookies from Remix Utils lets you use Zod to parse the cookie values and ensure they conform to a schema.
1import { createCookie } from "remix"; 2import { createTypedCookie } from "remix-utils"; 3import { z } from "zod"; 4 5let cookie = createCookie("returnTo", cookieOptions); 6let schema = z.string().url(); 7 8// pass the cookie and the schema 9let typedCookie = createTypedCookie({ cookie, schema }); 10 11// this will be a string and also a URL 12let returnTo = await typedCookie.parse(request.headers.get("Cookie")); 13 14// this will not pass the schema validation and throw a ZodError 15await cookie.serialize("a random string that's not a URL"); 16// this will make TS yell because it's not a string, if you ignore it it will 17// throw a ZodError 18await cookie.serialize(123);
You could also use typed cookies with any sessionStorage mechanism from Remix.
1let cookie = createCookie("session", cookieOptions);
2let schema = z.object({ token: z.string() });
3
4let sessionStorage = createCookieSessionStorage({
5 cookie: createTypedCookie({ cookie, schema }),
6});
7
8// if this works then the correct data is stored in the session
9let session = sessionStorage.getSession(request.headers.get("Cookie"));
10
11session.unset("token"); // remove a required key from the session
12
13// this will throw a ZodError because the session is missing the required key
14await sessionStorage.commitSession(session);
Now Zod will ensure the data you try to save to the session is valid removing any extra field and throwing if you don't set the correct data in the session.
Note The session object is not really typed so doing session.get will not return the correct type, you can do
schema.parse(session.data)
to get the typed version of the session data.
You can also use async refinements in your schemas because typed cookies uses parseAsync method from Zod.
1let cookie = createCookie("session", cookieOptions);
2
3let schema = z.object({
4 token: z.string().refine(async (token) => {
5 let user = await getUserByToken(token);
6 return user !== null;
7 }, "INVALID_TOKEN"),
8});
9
10let sessionTypedCookie = createTypedCookie({ cookie, schema });
11
12// this will throw if the token stored in the cookie is not valid anymore
13sessionTypedCookie.parse(request.headers.get("Cookie"));
Session objects in Remix allows any type, the typed sessions from Remix Utils lets you use Zod to parse the session data and ensure they conform to a schema.
1import { createCookieSessionStorage } from "remix";
2import { createTypedSessionStorage } from "remix-utils";
3import { z } from "zod";
4
5let schema = z.object({
6 token: z.string().optiona(),
7 count: z.number().default(1),
8});
9
10// you can use a Remix's Cookie container or a Remix Utils's Typed Cookie container
11let sessionStorage = createCookieSessionStorage({ cookie });
12
13// pass the session storage and the schema
14let typedSessionStorage = createTypedSessionStorage({ sessionStorage, schema });
Now you can use typedSessionStorage as a drop-in replacement for your normal sessionStorage.
1let session = typedSessionStorage.getSession(request.headers.get("Cookie")); 2 3session.get("token"); // this will be a string or undefined 4session.get("count"); // this will be a number 5session.get("random"); // this will make TS yell because it's not in the schema 6 7session.has("token"); // this will be a boolean 8session.has("count"); // this will be a boolean 9 10// this will make TS yell because it's not a string, if you ignore it it will 11// throw a ZodError 12session.set("token", 123);
Now Zod will ensure the data you try to save to the session is valid by not allowing you to get, set or unset data.
Note Remember that you either need to mark fields as optional or set a default value in the schema, otherwise it will be impossible to call getSession to get a new session object.
You can also use async refinements in your schemas because typed sesions uses parseAsync method from Zod.
1let schema = z.object({
2 token: z
3 .string()
4 .optional()
5 .refine(async (token) => {
6 if (!token) return true; // handle optionallity
7 let user = await getUserByToken(token);
8 return user !== null;
9 }, "INVALID_TOKEN"),
10});
11
12let typedSessionStorage = createTypedSessionStorage({ sessionStorage, schema });
13
14// this will throw if the token stored in the session is not valid anymore
15typedSessionStorage.getSession(request.headers.get("Cookie"));
Server-Sent Events are a way to send data from the server to the client without the need for the client to request it. This is useful for things like chat applications, live updates, and more.
There are two utils provided to help with the usage inside Remix:
eventStream
useEventSource
The eventStream
function is used to create a new event stream response needed to send events to the client.
1import { eventStream } from "remix-utils"; 2 3export async function loader({ request }: LoaderArgs) { 4 return eventStream(request.signal, function setup(send) { 5 let timer = setInterval(() => { 6 send({ event: "time", data: new Date().toISOString() }); 7 }, 1000); 8 9 return function clear() { 10 clearInterval(timer); 11 }; 12 }); 13}
Then, inside any component, you can use the useEventSource
hook to connect to the event stream.
1import { useEventSource } from "remix-utils";
2
3function Counter() {
4 let time = useEventSource("/sse/time", { event: "time" });
5
6 if (!time) return null;
7
8 return (
9 <time dateTime={time}>
10 {new Date(time).toLocaleTimeString("en", {
11 minute: "2-digit",
12 second: "2-digit",
13 hour: "2-digit",
14 })}
15 </time>
16 );
17}
The event
name in both the event stream and the hook is optional, in which case it will default to message
, if defined you must use the same event name in both sides, this also allows you to emit different events from the same event stream.
Rolling cookies allows you to prolong the expiration of a cookie by updating the expiration date of every cookie.
The rollingCookie
function is prepared to be used in entry.server
exported function to update the expiration date of a cookie if no loader set it.
For document request you can use it on the handleRequest
function:
1import { rollingCookie } from "remix-utils"; 2 3import { sessionCookie } from "~/session.server"; 4 5export default function handleRequest( 6 request: Request, 7 responseStatusCode: number, 8 responseHeaders: Headers, 9 remixContext: EntryContext 10) { 11 await rollingCookie(sessionCookie, request, responseHeaders); 12 13 return isbot(request.headers.get("user-agent")) 14 ? handleBotRequest( 15 request, 16 responseStatusCode, 17 responseHeaders, 18 remixContext 19 ) 20 : handleBrowserRequest( 21 request, 22 responseStatusCode, 23 responseHeaders, 24 remixContext 25 ); 26}
And for data request you can do it on the handleDataRequest
function:
1export let handleDataRequest: HandleDataRequestFunction = async ( 2 response: Response, 3 { request } 4) => { 5 let cookieValue = await sessionCookie.parse( 6 responseHeaders.get("set-cookie") 7 ); 8 if (!cookieValue) { 9 cookieValue = await sessionCookie.parse(request.headers.get("cookie")); 10 responseHeaders.append( 11 "Set-Cookie", 12 await sessionCookie.serialize(cookieValue) 13 ); 14 } 15 16 return response; 17};
It's common to need to handle more than one action in the same route, there are many options here like sending the form to a resource route or using an action reducer, the namedAction
function uses some conventions to implement the action reducer pattern.
1import { namedAction } from "remix-utils"; 2 3export async function action({ request }: ActionArgs) { 4 return namedAction(request, { 5 async create() { 6 // do create 7 }, 8 async update() { 9 // do update 10 }, 11 async delete() { 12 // do delete 13 }, 14 }); 15} 16 17export default function Component() { 18 return ( 19 <> 20 <Form method="post" action="?/create"> 21 ... 22 </Form> 23 24 <Form method="post" action="?/update"> 25 ... 26 </Form> 27 28 <Form method="post" action="?/delete"> 29 ... 30 </Form> 31 </> 32 ); 33}
This function can follow many conventions
You can pass a FormData object to the namedAction
, then it will try to
/something
and use it as the action name removing the /
intent
and use the value as the action nameaction
and use the value as the action name_action
and use the value as the action nameYou can pass an URLSearchParams object to the namedAction
, then it will try to
/something
and use it as the action name removing the /
intent
and use the value as the action nameaction
and use the value as the action name_action
and use the value as the action nameYou can pass an URL object to the namedAction
, it will behave as with a URLSearchParams object.
You can pass a Request object to the namedAction
, then it will try to
new URL(request.url)
and use it as the URL objectrequest.formData()
and use it as the FormData objectIf, in any case, the action name is not found, the actionName
then the library will try to call an action named default
, similar to a switch
in JavaScript.
If the default
is not defined it will throw a ReferenceError with the message Action "${name}" not found
.
If the library couldn't found the name at all, it will throw a ReferenceError with the message Action name not found
No vulnerabilities found.
No security vulnerabilities found.