nuxt-backend 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +744 -0
- package/dist/convex/auth.config.d.ts +9 -0
- package/dist/convex/auth.config.d.ts.map +1 -0
- package/dist/convex/auth.config.js +14 -0
- package/dist/convex/auth.config.js.map +1 -0
- package/dist/convex/client/index.d.ts +12784 -0
- package/dist/convex/client/index.d.ts.map +1 -0
- package/dist/convex/client/index.js +230 -0
- package/dist/convex/client/index.js.map +1 -0
- package/dist/convex/component/_generated/api.d.ts +36 -0
- package/dist/convex/component/_generated/api.d.ts.map +1 -0
- package/dist/convex/component/_generated/api.js +31 -0
- package/dist/convex/component/_generated/api.js.map +1 -0
- package/dist/convex/component/_generated/component.d.ts +549 -0
- package/dist/convex/component/_generated/component.d.ts.map +1 -0
- package/dist/convex/component/_generated/component.js +11 -0
- package/dist/convex/component/_generated/component.js.map +1 -0
- package/dist/convex/component/_generated/dataModel.d.ts +46 -0
- package/dist/convex/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/convex/component/_generated/dataModel.js +11 -0
- package/dist/convex/component/_generated/dataModel.js.map +1 -0
- package/dist/convex/component/_generated/server.d.ts +121 -0
- package/dist/convex/component/_generated/server.d.ts.map +1 -0
- package/dist/convex/component/_generated/server.js +78 -0
- package/dist/convex/component/_generated/server.js.map +1 -0
- package/dist/convex/component/adapter.d.ts +3 -0
- package/dist/convex/component/adapter.d.ts.map +1 -0
- package/dist/convex/component/adapter.js +23 -0
- package/dist/convex/component/adapter.js.map +1 -0
- package/dist/convex/component/constants.d.ts +3 -0
- package/dist/convex/component/constants.d.ts.map +1 -0
- package/dist/convex/component/constants.js +3 -0
- package/dist/convex/component/constants.js.map +1 -0
- package/dist/convex/component/convex.config.d.ts +14 -0
- package/dist/convex/component/convex.config.d.ts.map +1 -0
- package/dist/convex/component/convex.config.js +15 -0
- package/dist/convex/component/convex.config.js.map +1 -0
- package/dist/convex/component/schema.d.ts +278 -0
- package/dist/convex/component/schema.d.ts.map +1 -0
- package/dist/convex/component/schema.js +91 -0
- package/dist/convex/component/schema.js.map +1 -0
- package/dist/module.d.ts +47 -0
- package/dist/module.js +275 -0
- package/dist/module.json +9 -0
- package/dist/runtime/nuxt/auth/middleware.d.ts +12 -0
- package/dist/runtime/nuxt/auth/middleware.js +31 -0
- package/dist/runtime/nuxt/auth/proxy.d.ts +6 -0
- package/dist/runtime/nuxt/auth/proxy.js +11 -0
- package/dist/runtime/nuxt/auth/server.d.ts +86 -0
- package/dist/runtime/nuxt/auth/server.js +110 -0
- package/dist/runtime/nuxt/config.d.ts +7 -0
- package/dist/runtime/nuxt/config.js +12 -0
- package/dist/runtime/nuxt/index.d.ts +102 -0
- package/dist/runtime/nuxt/index.js +77 -0
- package/dist/runtime/vue/auth/client.d.ts +14 -0
- package/dist/runtime/vue/auth/client.js +7 -0
- package/dist/runtime/vue/auth/cross-domain.d.ts +8 -0
- package/dist/runtime/vue/auth/cross-domain.js +34 -0
- package/dist/runtime/vue/auth/helpers.d.ts +52 -0
- package/dist/runtime/vue/auth/helpers.js +35 -0
- package/dist/runtime/vue/auth/hydration.d.ts +14 -0
- package/dist/runtime/vue/auth/hydration.js +23 -0
- package/dist/runtime/vue/auth/index.d.ts +79 -0
- package/dist/runtime/vue/auth/index.js +81 -0
- package/dist/runtime/vue/auth/plugin.client.d.ts +6 -0
- package/dist/runtime/vue/auth/plugin.client.js +30 -0
- package/dist/runtime/vue/auth/plugin.server.d.ts +17 -0
- package/dist/runtime/vue/auth/plugin.server.js +29 -0
- package/dist/runtime/vue/auth/use-auth.d.ts +84 -0
- package/dist/runtime/vue/auth/use-auth.js +77 -0
- package/dist/runtime/vue/client.d.ts +245 -0
- package/dist/runtime/vue/client.js +341 -0
- package/dist/runtime/vue/composables/use-action.d.ts +45 -0
- package/dist/runtime/vue/composables/use-action.js +10 -0
- package/dist/runtime/vue/composables/use-connection-state.d.ts +25 -0
- package/dist/runtime/vue/composables/use-connection-state.js +13 -0
- package/dist/runtime/vue/composables/use-mutation.d.ts +60 -0
- package/dist/runtime/vue/composables/use-mutation.js +36 -0
- package/dist/runtime/vue/composables/use-paginated-query.d.ts +101 -0
- package/dist/runtime/vue/composables/use-paginated-query.js +508 -0
- package/dist/runtime/vue/composables/use-queries.d.ts +45 -0
- package/dist/runtime/vue/composables/use-queries.js +32 -0
- package/dist/runtime/vue/composables/use-query.d.ts +82 -0
- package/dist/runtime/vue/composables/use-query.js +63 -0
- package/dist/runtime/vue/composables/use-subscription.d.ts +14 -0
- package/dist/runtime/vue/composables/use-subscription.js +15 -0
- package/dist/runtime/vue/hydration.d.ts +42 -0
- package/dist/runtime/vue/hydration.js +18 -0
- package/dist/runtime/vue/index.d.ts +29 -0
- package/dist/runtime/vue/index.js +38 -0
- package/dist/runtime/vue/queries-observer.d.ts +38 -0
- package/dist/runtime/vue/queries-observer.js +127 -0
- package/dist/types.d.ts +3 -0
- package/package.json +157 -0
- package/src/convex/auth.config.ts +21 -0
- package/src/convex/client/index.ts +329 -0
- package/src/convex/component/_generated/api.ts +52 -0
- package/src/convex/component/_generated/component.ts +1338 -0
- package/src/convex/component/_generated/dataModel.ts +60 -0
- package/src/convex/component/_generated/server.ts +156 -0
- package/src/convex/component/adapter.ts +42 -0
- package/src/convex/component/constants.ts +2 -0
- package/src/convex/component/convex.config.ts +16 -0
- package/src/convex/component/schema.ts +93 -0
- package/src/convex/test.ts +34 -0
package/dist/module.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { defineNuxtModule, createResolver, addPlugin, addImports, addComponent, addServerHandler, addRouteMiddleware, addServerImports } from '@nuxt/kit';
|
|
2
|
+
import { join, dirname } from 'node:path';
|
|
3
|
+
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
|
|
4
|
+
import dedent from 'dedent';
|
|
5
|
+
|
|
6
|
+
const AUTH_CONFIG_TEMPLATE = `export { default } from 'nuxt-backend/convex/auth.config'
|
|
7
|
+
`;
|
|
8
|
+
const HTTP_TEMPLATE = dedent`
|
|
9
|
+
import { httpRouter } from 'convex/server'
|
|
10
|
+
import { authComponent, createAuth } from './auth'
|
|
11
|
+
|
|
12
|
+
const http = httpRouter()
|
|
13
|
+
authComponent.registerRoutes(http, createAuth)
|
|
14
|
+
|
|
15
|
+
export default http
|
|
16
|
+
` + "\n";
|
|
17
|
+
const BACKEND_FILE_TEMPLATES = {
|
|
18
|
+
"convex.config.ts": dedent`
|
|
19
|
+
import { defineApp } from 'convex/server'
|
|
20
|
+
import backend from 'nuxt-backend/convex/component/convex.config'
|
|
21
|
+
|
|
22
|
+
const app = defineApp()
|
|
23
|
+
app.use(backend)
|
|
24
|
+
export default app
|
|
25
|
+
` + "\n",
|
|
26
|
+
"auth.config.ts": AUTH_CONFIG_TEMPLATE,
|
|
27
|
+
"auth.ts": dedent`
|
|
28
|
+
import { setupAuth } from 'nuxt-backend/convex'
|
|
29
|
+
import { components } from './_generated/api'
|
|
30
|
+
import { query } from './_generated/server'
|
|
31
|
+
|
|
32
|
+
export const {
|
|
33
|
+
authComponent,
|
|
34
|
+
createAuthOptions,
|
|
35
|
+
options,
|
|
36
|
+
createAuth,
|
|
37
|
+
getAuthUser,
|
|
38
|
+
} = setupAuth(components.backend, query)
|
|
39
|
+
` + "\n",
|
|
40
|
+
"http.ts": HTTP_TEMPLATE
|
|
41
|
+
};
|
|
42
|
+
const LOCAL_BACKEND_FILE_TEMPLATES = {
|
|
43
|
+
"convex.config.ts": dedent`
|
|
44
|
+
import { defineApp } from 'convex/server'
|
|
45
|
+
import backend from './components/backend/convex.config'
|
|
46
|
+
|
|
47
|
+
const app = defineApp()
|
|
48
|
+
app.use(backend)
|
|
49
|
+
export default app
|
|
50
|
+
` + "\n",
|
|
51
|
+
"auth.config.ts": AUTH_CONFIG_TEMPLATE,
|
|
52
|
+
"auth.ts": dedent`
|
|
53
|
+
import { setupAuth } from 'nuxt-backend/convex'
|
|
54
|
+
import { components } from './_generated/api'
|
|
55
|
+
import { query } from './_generated/server'
|
|
56
|
+
import schema from './components/backend/schema'
|
|
57
|
+
|
|
58
|
+
export const {
|
|
59
|
+
authComponent,
|
|
60
|
+
createAuthOptions,
|
|
61
|
+
options,
|
|
62
|
+
createAuth,
|
|
63
|
+
getAuthUser,
|
|
64
|
+
} = setupAuth(components.backend, query, { schema })
|
|
65
|
+
` + "\n",
|
|
66
|
+
"http.ts": HTTP_TEMPLATE,
|
|
67
|
+
"components/backend/convex.config.ts": dedent`
|
|
68
|
+
import { defineComponent } from 'convex/server'
|
|
69
|
+
|
|
70
|
+
export default defineComponent('backend')
|
|
71
|
+
` + "\n",
|
|
72
|
+
"components/backend/generated-schema.ts": `export { tables } from 'nuxt-backend/convex/component/schema'
|
|
73
|
+
`,
|
|
74
|
+
"components/backend/schema.ts": dedent`
|
|
75
|
+
import { defineSchema } from 'convex/server'
|
|
76
|
+
import { tables } from './generated-schema'
|
|
77
|
+
|
|
78
|
+
export default defineSchema({
|
|
79
|
+
...tables,
|
|
80
|
+
})
|
|
81
|
+
` + "\n",
|
|
82
|
+
"components/backend/adapter.ts": dedent`
|
|
83
|
+
import { createApi } from '@convex-dev/better-auth'
|
|
84
|
+
import { createAuthOptions } from '../../auth'
|
|
85
|
+
import schema from './schema'
|
|
86
|
+
|
|
87
|
+
export const {
|
|
88
|
+
create,
|
|
89
|
+
findOne,
|
|
90
|
+
findMany,
|
|
91
|
+
updateOne,
|
|
92
|
+
updateMany,
|
|
93
|
+
deleteOne,
|
|
94
|
+
deleteMany,
|
|
95
|
+
} = createApi(schema, createAuthOptions)
|
|
96
|
+
` + "\n",
|
|
97
|
+
"components/backend/auth.ts": dedent`
|
|
98
|
+
import { createAuth } from '../../auth'
|
|
99
|
+
|
|
100
|
+
export const auth = createAuth({} as any)
|
|
101
|
+
` + "\n"
|
|
102
|
+
};
|
|
103
|
+
function getBackendFileTemplates(options = {}) {
|
|
104
|
+
return options.installation === "local" ? LOCAL_BACKEND_FILE_TEMPLATES : BACKEND_FILE_TEMPLATES;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const DEFAULT_FUNCTIONS_DIR = "backend";
|
|
108
|
+
const STANDARD_FUNCTIONS_DIR = "convex";
|
|
109
|
+
function scaffoldBackendFiles(rootDir, options = {}) {
|
|
110
|
+
const functionsDir = resolveFunctionsDir(rootDir);
|
|
111
|
+
const functionsDirPath = join(rootDir, functionsDir);
|
|
112
|
+
const convexJsonPath = join(rootDir, "convex.json");
|
|
113
|
+
if (!existsSync(functionsDirPath)) {
|
|
114
|
+
mkdirSync(functionsDirPath, { recursive: true });
|
|
115
|
+
console.log(`[nuxt-backend] Created ${functionsDir}/ directory`);
|
|
116
|
+
}
|
|
117
|
+
for (const [file, contents] of Object.entries(getBackendFileTemplates(options))) {
|
|
118
|
+
const targetPath = join(functionsDirPath, file);
|
|
119
|
+
if (!existsSync(targetPath)) {
|
|
120
|
+
mkdirSync(dirname(targetPath), { recursive: true });
|
|
121
|
+
writeFileSync(targetPath, contents);
|
|
122
|
+
console.log(`[nuxt-backend] Created ${functionsDir}/${file}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (functionsDir !== STANDARD_FUNCTIONS_DIR && !existsSync(convexJsonPath)) {
|
|
126
|
+
writeFileSync(convexJsonPath, `${JSON.stringify({ functions: `${functionsDir}/` }, null, 2)}
|
|
127
|
+
`);
|
|
128
|
+
console.log("[nuxt-backend] Created convex.json");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function resolveFunctionsDir(rootDir) {
|
|
132
|
+
const convexJsonPath = join(rootDir, "convex.json");
|
|
133
|
+
const configuredFunctionsDir = readFunctionsDirFromConvexJson(convexJsonPath);
|
|
134
|
+
if (configuredFunctionsDir) {
|
|
135
|
+
return configuredFunctionsDir;
|
|
136
|
+
}
|
|
137
|
+
if (existsSync(join(rootDir, DEFAULT_FUNCTIONS_DIR))) {
|
|
138
|
+
return DEFAULT_FUNCTIONS_DIR;
|
|
139
|
+
}
|
|
140
|
+
if (existsSync(join(rootDir, STANDARD_FUNCTIONS_DIR))) {
|
|
141
|
+
return STANDARD_FUNCTIONS_DIR;
|
|
142
|
+
}
|
|
143
|
+
return DEFAULT_FUNCTIONS_DIR;
|
|
144
|
+
}
|
|
145
|
+
function readFunctionsDirFromConvexJson(convexJsonPath) {
|
|
146
|
+
if (!existsSync(convexJsonPath)) {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
const convexJson = JSON.parse(readFileSync(convexJsonPath, "utf-8"));
|
|
151
|
+
if (typeof convexJson.functions !== "string") {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const normalizedFunctionsDir = normalizeFunctionsDir(convexJson.functions);
|
|
155
|
+
return normalizedFunctionsDir || void 0;
|
|
156
|
+
} catch (error) {
|
|
157
|
+
console.warn(`[nuxt-backend] Failed to parse convex.json: ${error instanceof Error ? error.message : String(error)}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function normalizeFunctionsDir(functionsDir) {
|
|
161
|
+
const normalized = functionsDir.replace(/^\.?\//, "").replace(/\/+$/, "");
|
|
162
|
+
return normalized || void 0;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const module$1 = defineNuxtModule({
|
|
166
|
+
meta: {
|
|
167
|
+
name: "nuxt-backend",
|
|
168
|
+
configKey: "backend"
|
|
169
|
+
},
|
|
170
|
+
defaults: {
|
|
171
|
+
authRoute: "/api/auth",
|
|
172
|
+
installation: "default"
|
|
173
|
+
},
|
|
174
|
+
setup(options, nuxt) {
|
|
175
|
+
const resolver = createResolver(import.meta.url);
|
|
176
|
+
const authRoute = options.authRoute || "/api/auth";
|
|
177
|
+
applyRuntimeConfig(nuxt, options);
|
|
178
|
+
scaffoldBackendFiles(nuxt.options.rootDir, { installation: options.installation });
|
|
179
|
+
registerBackendAliases(nuxt);
|
|
180
|
+
registerAuthPlugins(resolver);
|
|
181
|
+
registerVueComposables(resolver);
|
|
182
|
+
registerAuthComponents(resolver);
|
|
183
|
+
registerAuthServerHandlers(resolver, authRoute);
|
|
184
|
+
registerServerImports(resolver);
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
function applyRuntimeConfig(nuxt, options) {
|
|
188
|
+
const url = nuxt.options._prepare ? void 0 : options.url || process.env.NUXT_PUBLIC_CONVEX_URL;
|
|
189
|
+
if (!url && !nuxt.options._prepare) {
|
|
190
|
+
console.warn("[nuxt-backend] No Convex URL configured. Set `backend.url` in nuxt.config or NUXT_PUBLIC_CONVEX_URL.");
|
|
191
|
+
}
|
|
192
|
+
const siteUrl = options.siteUrl || process.env.NUXT_PUBLIC_CONVEX_SITE_URL || "";
|
|
193
|
+
nuxt.options.runtimeConfig.public.backend = {
|
|
194
|
+
url: url || "",
|
|
195
|
+
siteUrl
|
|
196
|
+
};
|
|
197
|
+
nuxt.options.runtimeConfig.backend = { siteUrl };
|
|
198
|
+
}
|
|
199
|
+
function getBackendAliases(rootDir) {
|
|
200
|
+
const functionsDir = resolveFunctionsDir(rootDir);
|
|
201
|
+
const backendDir = join(rootDir, functionsDir);
|
|
202
|
+
const generatedDir = join(backendDir, "_generated");
|
|
203
|
+
return {
|
|
204
|
+
"#backend/api": join(generatedDir, "api"),
|
|
205
|
+
"#backend/server": join(generatedDir, "server"),
|
|
206
|
+
"#backend/dataModel": join(generatedDir, "dataModel"),
|
|
207
|
+
"#backend/_generated": generatedDir,
|
|
208
|
+
"#backend": backendDir
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
function registerBackendAliases(nuxt) {
|
|
212
|
+
const aliases = getBackendAliases(nuxt.options.rootDir);
|
|
213
|
+
nuxt.options.nitro ||= {};
|
|
214
|
+
nuxt.options.nitro.alias ||= {};
|
|
215
|
+
for (const [alias, target] of Object.entries(aliases)) {
|
|
216
|
+
nuxt.options.alias[alias] = target;
|
|
217
|
+
nuxt.options.nitro.alias[alias] = target;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
function registerAuthPlugins(resolver) {
|
|
221
|
+
addPlugin(resolver.resolve("./runtime/vue/auth/plugin.client"));
|
|
222
|
+
addPlugin(resolver.resolve("./runtime/vue/auth/plugin.server"));
|
|
223
|
+
}
|
|
224
|
+
function registerVueComposables(resolver) {
|
|
225
|
+
const composables = [
|
|
226
|
+
{ name: "useConvex", from: resolver.resolve("./runtime/vue/client") },
|
|
227
|
+
{ name: "useQuery", from: resolver.resolve("./runtime/vue/composables/use-query") },
|
|
228
|
+
{ name: "useQuery_experimental", from: resolver.resolve("./runtime/vue/composables/use-query") },
|
|
229
|
+
{ name: "useConvexQuery", from: resolver.resolve("./runtime/vue/composables/use-query") },
|
|
230
|
+
{ name: "useQueries", from: resolver.resolve("./runtime/vue/composables/use-queries") },
|
|
231
|
+
{ name: "useConvexQueries", from: resolver.resolve("./runtime/vue/composables/use-queries") },
|
|
232
|
+
{ name: "useMutation", from: resolver.resolve("./runtime/vue/composables/use-mutation") },
|
|
233
|
+
{ name: "useConvexMutation", from: resolver.resolve("./runtime/vue/composables/use-mutation") },
|
|
234
|
+
{ name: "useAction", from: resolver.resolve("./runtime/vue/composables/use-action") },
|
|
235
|
+
{ name: "useConvexAction", from: resolver.resolve("./runtime/vue/composables/use-action") },
|
|
236
|
+
{ name: "useConvexConnectionState", from: resolver.resolve("./runtime/vue/composables/use-connection-state") },
|
|
237
|
+
{ name: "useConvexAuth", from: resolver.resolve("./runtime/vue/auth/index") },
|
|
238
|
+
{ name: "provideConvexAuth", from: resolver.resolve("./runtime/vue/auth/index") },
|
|
239
|
+
{ name: "usePreloadedQuery", from: resolver.resolve("./runtime/vue/hydration") },
|
|
240
|
+
{ name: "usePreloadedAuthQuery", from: resolver.resolve("./runtime/vue/auth/hydration") },
|
|
241
|
+
{ name: "usePaginatedQuery", from: resolver.resolve("./runtime/vue/composables/use-paginated-query") },
|
|
242
|
+
{ name: "usePaginatedQuery_experimental", from: resolver.resolve("./runtime/vue/composables/use-paginated-query") },
|
|
243
|
+
{ name: "useAuth", from: resolver.resolve("./runtime/vue/auth/use-auth") }
|
|
244
|
+
];
|
|
245
|
+
for (const composable of composables) {
|
|
246
|
+
addImports(composable);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function registerAuthComponents(resolver) {
|
|
250
|
+
const helpersFile = resolver.resolve("./runtime/vue/auth/helpers");
|
|
251
|
+
for (const name of ["Authenticated", "Unauthenticated", "AuthLoading"]) {
|
|
252
|
+
addComponent({ name, filePath: helpersFile, export: name });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function registerAuthServerHandlers(resolver, authRoute) {
|
|
256
|
+
addServerHandler({
|
|
257
|
+
route: `${authRoute}/**`,
|
|
258
|
+
handler: resolver.resolve("./runtime/nuxt/auth/proxy")
|
|
259
|
+
});
|
|
260
|
+
addRouteMiddleware({
|
|
261
|
+
name: "auth",
|
|
262
|
+
path: resolver.resolve("./runtime/nuxt/auth/middleware"),
|
|
263
|
+
global: false
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
function registerServerImports(resolver) {
|
|
267
|
+
const fromNuxt = resolver.resolve("./runtime/nuxt/index");
|
|
268
|
+
const serverUtils = ["fetchQuery", "fetchMutation", "fetchAction", "preloadQuery", "preloadedQueryResult"];
|
|
269
|
+
addServerImports(serverUtils.map((name) => ({ name, from: fromNuxt })));
|
|
270
|
+
addServerImports([
|
|
271
|
+
{ name: "backendAuth", from: resolver.resolve("./runtime/nuxt/auth/server") }
|
|
272
|
+
]);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export { module$1 as default, getBackendAliases };
|
package/dist/module.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth route middleware — protects pages from unauthenticated access.
|
|
3
|
+
*
|
|
4
|
+
* Usage in page:
|
|
5
|
+
* ```vue
|
|
6
|
+
* <script setup>
|
|
7
|
+
* definePageMeta({ middleware: 'auth' })
|
|
8
|
+
* </script>
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
declare const _default: import("#app").RouteMiddleware;
|
|
12
|
+
export default _default;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { defineNuxtRouteMiddleware, navigateTo, useRequestEvent } from "#app";
|
|
2
|
+
import { watch } from "vue";
|
|
3
|
+
import { useAuth } from "../../vue/auth/use-auth.js";
|
|
4
|
+
import { backendAuth } from "./server.js";
|
|
5
|
+
export default defineNuxtRouteMiddleware(async (to) => {
|
|
6
|
+
if (import.meta.server) {
|
|
7
|
+
const event = useRequestEvent();
|
|
8
|
+
if (!event) return;
|
|
9
|
+
const authed = await backendAuth(event).isAuthenticated();
|
|
10
|
+
if (!authed && to.path !== "/login") return navigateTo("/login");
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
const { session } = useAuth();
|
|
14
|
+
if (session.value.isPending) {
|
|
15
|
+
await new Promise((resolve) => {
|
|
16
|
+
const stop = watch(
|
|
17
|
+
() => session.value.isPending,
|
|
18
|
+
(pending) => {
|
|
19
|
+
if (!pending) {
|
|
20
|
+
stop();
|
|
21
|
+
resolve();
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
{ immediate: true }
|
|
25
|
+
);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
if (!session.value.data) {
|
|
29
|
+
return navigateTo("/login");
|
|
30
|
+
}
|
|
31
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineEventHandler } from "h3";
|
|
2
|
+
import { useRuntimeConfig } from "#imports";
|
|
3
|
+
import { backendAuth } from "./server.js";
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const config = useRuntimeConfig();
|
|
6
|
+
const siteUrl = config.backend.siteUrl;
|
|
7
|
+
if (!siteUrl) {
|
|
8
|
+
throw new Error("[nuxt-backend] NUXT_PUBLIC_CONVEX_SITE_URL is not configured. Auth proxy cannot forward requests.");
|
|
9
|
+
}
|
|
10
|
+
return backendAuth(event, { convexSiteUrl: siteUrl }).handler();
|
|
11
|
+
});
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side Better Auth + Convex integration for Nuxt.
|
|
3
|
+
*
|
|
4
|
+
* Provides {@link backendAuth} for Nuxt server handlers.
|
|
5
|
+
*
|
|
6
|
+
* It accepts the H3
|
|
7
|
+
* {@link H3Event} that is available in every Nuxt server route, API handler
|
|
8
|
+
* and server middleware.
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import type { H3Event } from 'h3';
|
|
13
|
+
import type { GetTokenOptions } from '@convex-dev/better-auth/utils';
|
|
14
|
+
import type { FunctionReference, FunctionReturnType } from 'convex/server';
|
|
15
|
+
import type { Preloaded } from '../../vue/hydration.js';
|
|
16
|
+
/**
|
|
17
|
+
* Options for {@link backendAuth}.
|
|
18
|
+
*
|
|
19
|
+
* Extends {@link GetTokenOptions} from `@convex-dev/better-auth/utils` with
|
|
20
|
+
* an optional override for the Convex site URL.
|
|
21
|
+
*
|
|
22
|
+
* @public
|
|
23
|
+
*/
|
|
24
|
+
export type BackendAuthOptions = GetTokenOptions & {
|
|
25
|
+
/**
|
|
26
|
+
* Override the Convex site URL. Defaults to `NUXT_PUBLIC_CONVEX_SITE_URL`.
|
|
27
|
+
*/
|
|
28
|
+
convexSiteUrl?: string;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Per-request Better Auth + Convex helper returned by {@link backendAuth}.
|
|
32
|
+
*
|
|
33
|
+
* @public
|
|
34
|
+
*/
|
|
35
|
+
export interface BackendAuthService {
|
|
36
|
+
/** Convex JWT for the current user, or `undefined` when not authenticated. */
|
|
37
|
+
getToken: () => Promise<string | undefined>;
|
|
38
|
+
/** `true` when the current request has a valid Convex auth token. */
|
|
39
|
+
isAuthenticated: () => Promise<boolean>;
|
|
40
|
+
/** Proxy a Better Auth route to the configured Convex site URL. */
|
|
41
|
+
handler: () => Promise<Response>;
|
|
42
|
+
/** Preload a Convex query with the current user's auth token. */
|
|
43
|
+
preloadAuthQuery: <Query extends FunctionReference<'query'>>(query: Query, args?: Query['_args']) => Promise<Preloaded<Query>>;
|
|
44
|
+
/** Execute a Convex query with the current user's auth token. */
|
|
45
|
+
fetchAuthQuery: <Query extends FunctionReference<'query'>>(query: Query, args?: Query['_args']) => Promise<FunctionReturnType<Query>>;
|
|
46
|
+
/** Execute a Convex mutation with the current user's auth token. */
|
|
47
|
+
fetchAuthMutation: <Mutation extends FunctionReference<'mutation'>>(mutation: Mutation, args?: Mutation['_args']) => Promise<FunctionReturnType<Mutation>>;
|
|
48
|
+
/** Execute a Convex action with the current user's auth token. */
|
|
49
|
+
fetchAuthAction: <Action extends FunctionReference<'action'>>(action: Action, args?: Action['_args']) => Promise<FunctionReturnType<Action>>;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Create a per-request Better Auth + Convex helper for Nuxt server code.
|
|
53
|
+
*
|
|
54
|
+
* Adapts the Better Auth + Convex server helper pattern to H3 events.
|
|
55
|
+
*
|
|
56
|
+
* Call once at the top of a server route / event handler and destructure the
|
|
57
|
+
* helpers you need. The auth token is fetched at most once per request (cached
|
|
58
|
+
* inside the returned object).
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```ts
|
|
62
|
+
* // server/api/profile.get.ts
|
|
63
|
+
* export default defineEventHandler(async (event) => {
|
|
64
|
+
* const { fetchAuthQuery, isAuthenticated } = backendAuth(event)
|
|
65
|
+
* if (!await isAuthenticated()) {
|
|
66
|
+
* throw createError({ statusCode: 401 })
|
|
67
|
+
* }
|
|
68
|
+
* return fetchAuthQuery(api.users.current)
|
|
69
|
+
* })
|
|
70
|
+
* ```
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```ts
|
|
74
|
+
* // pages/profile.vue — preloading data for SSR
|
|
75
|
+
* const { data } = await useAsyncData(async () => {
|
|
76
|
+
* const event = useRequestEvent()!
|
|
77
|
+
* return backendAuth(event).preloadAuthQuery(api.users.current)
|
|
78
|
+
* })
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
81
|
+
* @param event - The H3 event from a Nuxt server route or middleware.
|
|
82
|
+
* @param opts - Optional {@link BackendAuthOptions}.
|
|
83
|
+
*
|
|
84
|
+
* @public
|
|
85
|
+
*/
|
|
86
|
+
export declare function backendAuth(event: H3Event, opts?: BackendAuthOptions): BackendAuthService;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { getRequestHeaders, toWebRequest } from "h3";
|
|
2
|
+
import { getToken } from "@convex-dev/better-auth/utils";
|
|
3
|
+
import { getBackendRuntimeConfig } from "../config.js";
|
|
4
|
+
import { fetchAction, fetchMutation, fetchQuery, preloadQuery } from "../index.js";
|
|
5
|
+
function getConvexSiteUrl(override) {
|
|
6
|
+
const runtimeSiteUrl = getBackendRuntimeConfig().siteUrl;
|
|
7
|
+
const url = override ?? runtimeSiteUrl ?? process.env.NUXT_PUBLIC_CONVEX_SITE_URL;
|
|
8
|
+
if (!url) {
|
|
9
|
+
throw new Error(
|
|
10
|
+
"Environment variable NUXT_PUBLIC_CONVEX_SITE_URL is not set. This is required to fetch a Convex auth token server-side. Set it in your .env file or via the `backend.siteUrl` option in nuxt.config."
|
|
11
|
+
);
|
|
12
|
+
}
|
|
13
|
+
if (url.endsWith(".convex.cloud")) {
|
|
14
|
+
throw new Error(
|
|
15
|
+
`NUXT_PUBLIC_CONVEX_SITE_URL should be your Convex Site URL (ending in .convex.site), but it is currently set to ${url}.`
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
return url;
|
|
19
|
+
}
|
|
20
|
+
export function backendAuth(event, opts) {
|
|
21
|
+
const siteUrl = getConvexSiteUrl(opts?.convexSiteUrl);
|
|
22
|
+
let cached = null;
|
|
23
|
+
const getCachedToken = async ({ forceRefresh = false } = {}) => {
|
|
24
|
+
if (cached && !forceRefresh) return cached;
|
|
25
|
+
const rawHeaders = getRequestHeaders(event);
|
|
26
|
+
const headers = new Headers(rawHeaders);
|
|
27
|
+
headers.delete("content-length");
|
|
28
|
+
headers.delete("transfer-encoding");
|
|
29
|
+
headers.set("accept-encoding", "identity");
|
|
30
|
+
cached = await getToken(siteUrl, headers, { ...opts, forceRefresh });
|
|
31
|
+
return cached;
|
|
32
|
+
};
|
|
33
|
+
const callWithToken = async (fn) => {
|
|
34
|
+
const tokenResult = await getCachedToken();
|
|
35
|
+
try {
|
|
36
|
+
return await fn(tokenResult.token);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (!opts?.jwtCache?.enabled || tokenResult.isFresh || !opts.jwtCache.isAuthError(error)) {
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
const freshResult = await getCachedToken({ forceRefresh: true });
|
|
42
|
+
return fn(freshResult.token);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const handler = async () => {
|
|
46
|
+
const request = toWebRequest(event);
|
|
47
|
+
const requestUrl = new URL(request.url);
|
|
48
|
+
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, siteUrl);
|
|
49
|
+
const headers = new Headers(request.headers);
|
|
50
|
+
const forwardedProto = requestUrl.protocol.slice(0, -1);
|
|
51
|
+
const body = request.body === null || request.method === "GET" || request.method === "HEAD" ? void 0 : await request.arrayBuffer();
|
|
52
|
+
headers.set("host", targetUrl.host);
|
|
53
|
+
headers.set("x-forwarded-host", requestUrl.host);
|
|
54
|
+
headers.set("x-forwarded-proto", forwardedProto);
|
|
55
|
+
headers.set("x-better-auth-forwarded-host", requestUrl.host);
|
|
56
|
+
headers.set("x-better-auth-forwarded-proto", forwardedProto);
|
|
57
|
+
return fetch(new Request(targetUrl, {
|
|
58
|
+
method: request.method,
|
|
59
|
+
headers,
|
|
60
|
+
body,
|
|
61
|
+
redirect: "manual"
|
|
62
|
+
}));
|
|
63
|
+
};
|
|
64
|
+
return {
|
|
65
|
+
/**
|
|
66
|
+
* Return the Convex JWT for the current user, or `undefined` when the user
|
|
67
|
+
* is not authenticated.
|
|
68
|
+
*/
|
|
69
|
+
getToken: async () => {
|
|
70
|
+
const result = await getCachedToken();
|
|
71
|
+
return result.token;
|
|
72
|
+
},
|
|
73
|
+
/**
|
|
74
|
+
* Return `true` when the current request has a valid Convex auth token.
|
|
75
|
+
*/
|
|
76
|
+
isAuthenticated: async () => {
|
|
77
|
+
const result = await getCachedToken();
|
|
78
|
+
return !!result.token;
|
|
79
|
+
},
|
|
80
|
+
/**
|
|
81
|
+
* Proxy a Better Auth route to the configured Convex site URL.
|
|
82
|
+
*/
|
|
83
|
+
handler,
|
|
84
|
+
/**
|
|
85
|
+
* Preload a Convex query with the current user's auth token.
|
|
86
|
+
* Pass the result to `usePreloadedQuery` in a client component.
|
|
87
|
+
*/
|
|
88
|
+
preloadAuthQuery: (query, args) => callWithToken(
|
|
89
|
+
(token) => preloadQuery(query, args ?? {}, { token })
|
|
90
|
+
),
|
|
91
|
+
/**
|
|
92
|
+
* Execute a Convex query function with the current user's auth token.
|
|
93
|
+
*/
|
|
94
|
+
fetchAuthQuery: (query, args) => callWithToken(
|
|
95
|
+
(token) => fetchQuery(query, args ?? {}, { token })
|
|
96
|
+
),
|
|
97
|
+
/**
|
|
98
|
+
* Execute a Convex mutation function with the current user's auth token.
|
|
99
|
+
*/
|
|
100
|
+
fetchAuthMutation: (mutation, args) => callWithToken(
|
|
101
|
+
(token) => fetchMutation(mutation, args ?? {}, { token })
|
|
102
|
+
),
|
|
103
|
+
/**
|
|
104
|
+
* Execute a Convex action function with the current user's auth token.
|
|
105
|
+
*/
|
|
106
|
+
fetchAuthAction: (action, args) => callWithToken(
|
|
107
|
+
(token) => fetchAction(action, args ?? {}, { token })
|
|
108
|
+
)
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { useRuntimeConfig } from "#imports";
|
|
2
|
+
export function getBackendRuntimeConfig() {
|
|
3
|
+
try {
|
|
4
|
+
const config = useRuntimeConfig();
|
|
5
|
+
return {
|
|
6
|
+
url: config.public?.backend?.url,
|
|
7
|
+
siteUrl: config.backend?.siteUrl || config.public?.backend?.siteUrl
|
|
8
|
+
};
|
|
9
|
+
} catch {
|
|
10
|
+
return {};
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for integrating Convex into Nuxt applications using server rendering.
|
|
3
|
+
*
|
|
4
|
+
* This module contains:
|
|
5
|
+
* 1. {@link preloadQuery}, for preloading data for reactive client components.
|
|
6
|
+
* 2. {@link fetchQuery}, {@link fetchMutation} and {@link fetchAction} for loading
|
|
7
|
+
* and mutating Convex data from Nuxt server routes, API handlers, and middleware.
|
|
8
|
+
*
|
|
9
|
+
* All exported functions assume that a Convex deployment URL is set in the
|
|
10
|
+
* `NUXT_PUBLIC_CONVEX_URL` environment variable.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import type { ArgsAndOptions, FunctionReference, FunctionReturnType } from 'convex/server';
|
|
15
|
+
import type { Preloaded } from '../vue/hydration.js';
|
|
16
|
+
/**
|
|
17
|
+
* Options for {@link preloadQuery}, {@link fetchQuery}, {@link fetchMutation}
|
|
18
|
+
* and {@link fetchAction}.
|
|
19
|
+
*
|
|
20
|
+
* @public
|
|
21
|
+
*/
|
|
22
|
+
export interface NuxtConvexOptions {
|
|
23
|
+
/**
|
|
24
|
+
* The JWT-encoded OpenID Connect authentication token to use for the function call.
|
|
25
|
+
*/
|
|
26
|
+
token?: string;
|
|
27
|
+
/**
|
|
28
|
+
* The URL of the Convex deployment to use for the function call.
|
|
29
|
+
* Defaults to `process.env.NUXT_PUBLIC_CONVEX_URL` if not provided.
|
|
30
|
+
*
|
|
31
|
+
* Explicitly passing undefined here (such as from missing ENV variables) will throw an error in the future.
|
|
32
|
+
*/
|
|
33
|
+
url?: string;
|
|
34
|
+
/**
|
|
35
|
+
* @internal
|
|
36
|
+
*/
|
|
37
|
+
adminToken?: string;
|
|
38
|
+
/**
|
|
39
|
+
* Skip validating that the Convex deployment URL looks like
|
|
40
|
+
* `https://happy-animal-123.convex.cloud` or localhost.
|
|
41
|
+
*
|
|
42
|
+
* This can be useful if running a self-hosted Convex backend that uses a different
|
|
43
|
+
* URL.
|
|
44
|
+
*
|
|
45
|
+
* The default value is `false`
|
|
46
|
+
*/
|
|
47
|
+
skipConvexDeploymentUrlCheck?: boolean;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Execute a Convex query function and return a `Preloaded` payload
|
|
51
|
+
* which can be passed to `usePreloadedQuery` in a client component.
|
|
52
|
+
*
|
|
53
|
+
* @param query - A FunctionReference for the public query to run.
|
|
54
|
+
* @param args - The query arguments and optional {@link NuxtConvexOptions}
|
|
55
|
+
* passed as the final argument.
|
|
56
|
+
* @returns A promise of the `Preloaded` payload.
|
|
57
|
+
*
|
|
58
|
+
* @public
|
|
59
|
+
*/
|
|
60
|
+
export declare function preloadQuery<Query extends FunctionReference<'query'>>(query: Query, ...args: ArgsAndOptions<Query, NuxtConvexOptions>): Promise<Preloaded<Query>>;
|
|
61
|
+
/**
|
|
62
|
+
* Returns the result of executing a query via `preloadQuery`.
|
|
63
|
+
*
|
|
64
|
+
* @param preloaded - The `Preloaded` payload returned by `preloadQuery`.
|
|
65
|
+
* @returns The query result.
|
|
66
|
+
*
|
|
67
|
+
* @public
|
|
68
|
+
*/
|
|
69
|
+
export declare function preloadedQueryResult<Query extends FunctionReference<'query'>>(preloaded: Preloaded<Query>): FunctionReturnType<Query>;
|
|
70
|
+
/**
|
|
71
|
+
* Execute a Convex query function.
|
|
72
|
+
*
|
|
73
|
+
* @param query - A FunctionReference for the public query to run.
|
|
74
|
+
* @param args - The query arguments and optional {@link NuxtConvexOptions}
|
|
75
|
+
* passed as the final argument.
|
|
76
|
+
* @returns A promise of the query's result.
|
|
77
|
+
*
|
|
78
|
+
* @public
|
|
79
|
+
*/
|
|
80
|
+
export declare function fetchQuery<Query extends FunctionReference<'query'>>(query: Query, ...args: ArgsAndOptions<Query, NuxtConvexOptions>): Promise<FunctionReturnType<Query>>;
|
|
81
|
+
/**
|
|
82
|
+
* Execute a Convex mutation function.
|
|
83
|
+
*
|
|
84
|
+
* @param mutation - A FunctionReference for the public mutation to run.
|
|
85
|
+
* @param args - The mutation arguments and optional {@link NuxtConvexOptions}
|
|
86
|
+
* passed as the final argument.
|
|
87
|
+
* @returns A promise of the mutation's result.
|
|
88
|
+
*
|
|
89
|
+
* @public
|
|
90
|
+
*/
|
|
91
|
+
export declare function fetchMutation<Mutation extends FunctionReference<'mutation'>>(mutation: Mutation, ...args: ArgsAndOptions<Mutation, NuxtConvexOptions>): Promise<FunctionReturnType<Mutation>>;
|
|
92
|
+
/**
|
|
93
|
+
* Execute a Convex action function.
|
|
94
|
+
*
|
|
95
|
+
* @param action - A FunctionReference for the public action to run.
|
|
96
|
+
* @param args - The action arguments and optional {@link NuxtConvexOptions}
|
|
97
|
+
* passed as the final argument.
|
|
98
|
+
* @returns A promise of the action's result.
|
|
99
|
+
*
|
|
100
|
+
* @public
|
|
101
|
+
*/
|
|
102
|
+
export declare function fetchAction<Action extends FunctionReference<'action'>>(action: Action, ...args: ArgsAndOptions<Action, NuxtConvexOptions>): Promise<FunctionReturnType<Action>>;
|