Last active
August 9, 2024 09:56
-
-
Save AlemTuzlak/cb94f77b5e9f5d5a1d0fb119e9ace849 to your computer and use it in GitHub Desktop.
Hono auto-infer app context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Your app load context function that generates the remix context object | |
const generateAppLoadContext = async (c: Context, build: ServerBuild) => { | |
// example with i18n | |
const locale = i18next.getLocale(c); | |
const t = await i18next.getFixedT(c); | |
return { | |
appVersion: "v1.0", | |
lang: locale, | |
t, | |
}; | |
}; | |
// Create this utility interface from the above function | |
interface LoadContext extends Awaited<ReturnType<typeof generateAppLoadContext>> {} | |
/** | |
* Add remix middleware to Hono server | |
*/ | |
app.use(async (c, next) => { | |
const build = await import("../build/server/remix.js") | |
return remix({ | |
build, | |
mode, | |
// Add the function here | |
getLoadContext: () => generateAppLoadContext(c, build), | |
})(c, next); | |
}); | |
// Use the below to declare your App context with the return from the function, whenever you add something it's automatically typed | |
declare module "@remix-run/node" { | |
interface AppLoadContext extends LoadContext { | |
// No need to declare anything here anymore | |
} | |
} | |
// Then in your loaders: | |
export const loader = ({ context }: LoaderFunctionArgs) => { | |
console.log(context.appVersion) // "v1.0" fully typed | |
return { }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment