├── .eslintrc.cjs ├── .github └── workflows │ └── github-pages.yml ├── .gitignore ├── .prettierrc ├── LICENSE.txt ├── README.md ├── components.json ├── convex.json ├── convex ├── README.md ├── _generated │ ├── api.d.ts │ ├── api.js │ ├── dataModel.d.ts │ ├── server.d.ts │ └── server.js ├── auth.config.ts ├── auth.ts ├── crons.ts ├── data.ts ├── http.ts ├── images.ts ├── posts.ts ├── schema.ts ├── sharp.ts ├── tsconfig.json ├── users.ts └── versions.ts ├── index.html ├── package.json ├── postcss.config.js ├── public └── assets │ └── convex.svg ├── setup.mjs ├── src ├── components │ ├── Author │ │ ├── Edit.tsx │ │ └── Profile.tsx │ ├── Blog │ │ ├── Edit.tsx │ │ ├── History.tsx │ │ └── Post.tsx │ ├── Code.tsx │ ├── GetStarted │ │ ├── ConvexLogo.tsx │ │ └── GetStartedDialog.tsx │ ├── Inputs.tsx │ ├── Markdown.tsx │ ├── PageLayout.tsx │ ├── PageTitle.tsx │ ├── Search.tsx │ ├── SignIn │ │ ├── SignInDialog.tsx │ │ ├── SignInForm.tsx │ │ └── SignInMethodDivider.tsx │ ├── ThemeToggle.tsx │ ├── Toolbar.tsx │ ├── UserMenu.tsx │ └── ui │ │ ├── button.tsx │ │ ├── card.tsx │ │ ├── dialog.tsx │ │ ├── dropdown-menu.tsx │ │ ├── form.tsx │ │ ├── input.tsx │ │ ├── label.tsx │ │ ├── scroll-area.tsx │ │ ├── switch.tsx │ │ ├── textarea.tsx │ │ ├── toast.tsx │ │ ├── toaster.tsx │ │ ├── toggle-group.tsx │ │ ├── toggle.tsx │ │ └── use-toast.ts ├── index.css ├── lib │ └── utils.ts ├── main.tsx ├── pages │ ├── __layout.tsx │ └── __layout │ │ ├── $slug.tsx │ │ ├── __authed.tsx │ │ ├── __authed │ │ ├── $slug.edit.tsx │ │ ├── authors.$user.edit.tsx │ │ └── new.tsx │ │ ├── about.tsx │ │ ├── authors │ │ ├── $user.tsx │ │ └── index.tsx │ │ └── index.tsx └── vite-env.d.ts ├── tailwind.config.js ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.node.json ├── vercel.json └── vite.config.ts /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true, node: true }, 4 | extends: [ 5 | "eslint:recommended", 6 | "plugin:@typescript-eslint/recommended-type-checked", 7 | "plugin:react-hooks/recommended", 8 | ], 9 | ignorePatterns: [ 10 | "dist", 11 | ".eslintrc.cjs", 12 | "convex/_generated", 13 | "postcss.config.js", 14 | "tailwind.config.js", 15 | "vite.config.ts", 16 | // shadcn components by default violate some rules 17 | "src/components/ui", 18 | ], 19 | parser: "@typescript-eslint/parser", 20 | parserOptions: { 21 | EXPERIMENTAL_useProjectService: true, 22 | }, 23 | plugins: ["react-refresh"], 24 | rules: { 25 | "react-refresh/only-export-components": [ 26 | "warn", 27 | { allowConstantExport: true }, 28 | ], 29 | 30 | // All of these overrides ease getting into 31 | // TypeScript, and can be removed for stricter 32 | // linting down the line. 33 | 34 | // Only warn on unused variables, and ignore variables starting with `_` 35 | "@typescript-eslint/no-unused-vars": [ 36 | "warn", 37 | { varsIgnorePattern: "^_", argsIgnorePattern: "^_" }, 38 | ], 39 | 40 | // Allow escaping the compiler 41 | "@typescript-eslint/ban-ts-comment": "error", 42 | 43 | // Allow explicit `any`s 44 | "@typescript-eslint/no-explicit-any": "off", 45 | 46 | // START: Allow implicit `any`s 47 | "@typescript-eslint/no-unsafe-argument": "off", 48 | "@typescript-eslint/no-unsafe-assignment": "off", 49 | "@typescript-eslint/no-unsafe-call": "off", 50 | "@typescript-eslint/no-unsafe-member-access": "off", 51 | "@typescript-eslint/no-unsafe-return": "off", 52 | // END: Allow implicit `any`s 53 | 54 | // Allow async functions without await 55 | // for consistency (esp. Convex `handler`s) 56 | "@typescript-eslint/require-await": "off", 57 | }, 58 | }; 59 | -------------------------------------------------------------------------------- /.github/workflows/github-pages.yml: -------------------------------------------------------------------------------- 1 | # Simple workflow for deploying static content to GitHub Pages 2 | name: Deploy static content to Pages 3 | 4 | on: 5 | # Runs on pushes targeting the default branch 6 | push: 7 | branches: ['main'] 8 | 9 | # Allows you to run this workflow manually from the Actions tab 10 | workflow_dispatch: 11 | 12 | # Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages 13 | permissions: 14 | contents: read 15 | pages: write 16 | id-token: write 17 | 18 | # Allow one concurrent deployment 19 | concurrency: 20 | group: 'pages' 21 | cancel-in-progress: true 22 | 23 | 24 | 25 | 26 | jobs: 27 | # Single deploy job since we're just deploying 28 | deploy: 29 | environment: 30 | name: github-pages 31 | url: ${{ steps.deployment.outputs.page_url }} 32 | runs-on: ubuntu-latest 33 | env: 34 | VITE_CONVEX_URL: ${{ vars.VITE_CONVEX_URL }} 35 | steps: 36 | - name: Checkout 37 | uses: actions/checkout@v4 38 | - name: Set up Node 39 | uses: actions/setup-node@v4 40 | with: 41 | node-version: 20 42 | cache: 'npm' 43 | - name: Install dependencies 44 | run: npm ci 45 | - name: Build 46 | run: npm run build 47 | - name: Setup Pages 48 | uses: actions/configure-pages@v4 49 | - name: Upload artifact 50 | uses: actions/upload-pages-artifact@v3 51 | with: 52 | # Upload dist folder 53 | path: './dist' 54 | - name: Deploy to GitHub Pages 55 | id: deployment 56 | uses: actions/deploy-pages@v4 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2024 Convex, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Convex + React + Convex Auth 2 | 3 | This is a template for using [Convex](https://docs.convex.dev/) with React and [Convex Auth](https://labs.convex.dev/auth). 4 | 5 | ## Setting up 6 | 7 | ``` 8 | npm create convex@latest -- -t react-vite-convexauth-shadcn 9 | ``` 10 | 11 | Navigate to the new directory and run: 12 | 13 | ``` 14 | npm run dev 15 | ``` 16 | 17 | It'll walk you through the auth environment variables setup. 18 | 19 | ## The app 20 | 21 | The app is a basic multi-user chat. Walk through of the source code: 22 | 23 | - [convex/auth.ts](./convex/auth.ts) configures the available authentication methods 24 | - [convex/messages.ts](./convex/messages.ts) is the chat backend implementation 25 | - [src/main.tsx](./src/main.tsx) is the frontend entry-point 26 | - [src/App.tsx](./src/App.tsx) determines which UI to show based on the authentication state 27 | - [src/SignInForm.tsx](./src/SignInForm.tsx) implements the sign-in UI 28 | - [src/Chat/Chat.tsx](./src/Chat/Chat.tsx) is the chat frontend 29 | 30 | ## Configuring other authentication methods 31 | 32 | To configure different authentication methods, see [Configuration](https://labs.convex.dev/auth/config) in the Convex Auth docs. 33 | -------------------------------------------------------------------------------- /components.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://ui.shadcn.com/schema.json", 3 | "style": "new-york", 4 | "rsc": false, 5 | "tsx": true, 6 | "tailwind": { 7 | "config": "tailwind.config.js", 8 | "css": "src/index.css", 9 | "baseColor": "stone", 10 | "cssVariables": true, 11 | "prefix": "" 12 | }, 13 | "aliases": { 14 | "components": "@/components", 15 | "utils": "@/lib/utils" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /convex.json: -------------------------------------------------------------------------------- 1 | { 2 | "node": { 3 | "externalPackages": [ 4 | "sharp" 5 | ] 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /convex/README.md: -------------------------------------------------------------------------------- 1 | # Welcome to your Convex functions directory! 2 | 3 | Write your Convex functions here. 4 | See https://docs.convex.dev/functions for more. 5 | 6 | A query function that takes two arguments looks like: 7 | 8 | ```ts 9 | // functions.js 10 | import { query } from "./_generated/server"; 11 | import { v } from "convex/values"; 12 | 13 | export const myQueryFunction = query({ 14 | // Validators for arguments. 15 | args: { 16 | first: v.number(), 17 | second: v.string(), 18 | }, 19 | 20 | // Function implementation. 21 | handler: async (ctx, args) => { 22 | // Read the database as many times as you need here. 23 | // See https://docs.convex.dev/database/reading-data. 24 | const documents = await ctx.db.query("tablename").collect(); 25 | 26 | // Arguments passed from the client are properties of the args object. 27 | console.log(args.first, args.second); 28 | 29 | // Write arbitrary JavaScript here: filter, aggregate, build derived data, 30 | // remove non-public properties, or create new objects. 31 | return documents; 32 | }, 33 | }); 34 | ``` 35 | 36 | Using this query function in a React component looks like: 37 | 38 | ```ts 39 | const data = useQuery(api.functions.myQueryFunction, { 40 | first: 10, 41 | second: "hello", 42 | }); 43 | ``` 44 | 45 | A mutation function looks like: 46 | 47 | ```ts 48 | // functions.js 49 | import { mutation } from "./_generated/server"; 50 | import { v } from "convex/values"; 51 | 52 | export const myMutationFunction = mutation({ 53 | // Validators for arguments. 54 | args: { 55 | first: v.string(), 56 | second: v.string(), 57 | }, 58 | 59 | // Function implementation. 60 | handler: async (ctx, args) => { 61 | // Insert or modify documents in the database here. 62 | // Mutations can also read from the database like queries. 63 | // See https://docs.convex.dev/database/writing-data. 64 | const message = { body: args.first, author: args.second }; 65 | const id = await ctx.db.insert("messages", message); 66 | 67 | // Optionally, return a value from your mutation. 68 | return await ctx.db.get(id); 69 | }, 70 | }); 71 | ``` 72 | 73 | Using this mutation function in a React component looks like: 74 | 75 | ```ts 76 | const mutation = useMutation(api.functions.myMutationFunction); 77 | function handleButtonPress() { 78 | // fire and forget, the most common way to use mutations 79 | mutation({ first: "Hello!", second: "me" }); 80 | // OR 81 | // use the result once the mutation has completed 82 | mutation({ first: "Hello!", second: "me" }).then((result) => 83 | console.log(result), 84 | ); 85 | } 86 | ``` 87 | 88 | Use the Convex CLI to push your functions to a deployment. See everything 89 | the Convex CLI can do by running `npx convex -h` in your project root 90 | directory. To learn more, launch the docs with `npx convex docs`. 91 | -------------------------------------------------------------------------------- /convex/_generated/api.d.ts: -------------------------------------------------------------------------------- 1 | /* prettier-ignore-start */ 2 | 3 | /* eslint-disable */ 4 | /** 5 | * Generated `api` utility. 6 | * 7 | * THIS CODE IS AUTOMATICALLY GENERATED. 8 | * 9 | * To regenerate, run `npx convex dev`. 10 | * @module 11 | */ 12 | 13 | import type { 14 | ApiFromModules, 15 | FilterApi, 16 | FunctionReference, 17 | } from "convex/server"; 18 | import type * as auth from "../auth.js"; 19 | import type * as crons from "../crons.js"; 20 | import type * as data from "../data.js"; 21 | import type * as http from "../http.js"; 22 | import type * as images from "../images.js"; 23 | import type * as posts from "../posts.js"; 24 | import type * as sharp from "../sharp.js"; 25 | import type * as users from "../users.js"; 26 | import type * as versions from "../versions.js"; 27 | 28 | /** 29 | * A utility for referencing Convex functions in your app's API. 30 | * 31 | * Usage: 32 | * ```js 33 | * const myFunctionReference = api.myModule.myFunction; 34 | * ``` 35 | */ 36 | declare const fullApi: ApiFromModules<{ 37 | auth: typeof auth; 38 | crons: typeof crons; 39 | data: typeof data; 40 | http: typeof http; 41 | images: typeof images; 42 | posts: typeof posts; 43 | sharp: typeof sharp; 44 | users: typeof users; 45 | versions: typeof versions; 46 | }>; 47 | export declare const api: FilterApi< 48 | typeof fullApi, 49 | FunctionReference 50 | >; 51 | export declare const internal: FilterApi< 52 | typeof fullApi, 53 | FunctionReference 54 | >; 55 | 56 | /* prettier-ignore-end */ 57 | -------------------------------------------------------------------------------- /convex/_generated/api.js: -------------------------------------------------------------------------------- 1 | /* prettier-ignore-start */ 2 | 3 | /* eslint-disable */ 4 | /** 5 | * Generated `api` utility. 6 | * 7 | * THIS CODE IS AUTOMATICALLY GENERATED. 8 | * 9 | * To regenerate, run `npx convex dev`. 10 | * @module 11 | */ 12 | 13 | import { anyApi } from "convex/server"; 14 | 15 | /** 16 | * A utility for referencing Convex functions in your app's API. 17 | * 18 | * Usage: 19 | * ```js 20 | * const myFunctionReference = api.myModule.myFunction; 21 | * ``` 22 | */ 23 | export const api = anyApi; 24 | export const internal = anyApi; 25 | 26 | /* prettier-ignore-end */ 27 | -------------------------------------------------------------------------------- /convex/_generated/dataModel.d.ts: -------------------------------------------------------------------------------- 1 | /* prettier-ignore-start */ 2 | 3 | /* eslint-disable */ 4 | /** 5 | * Generated data model types. 6 | * 7 | * THIS CODE IS AUTOMATICALLY GENERATED. 8 | * 9 | * To regenerate, run `npx convex dev`. 10 | * @module 11 | */ 12 | 13 | import type { 14 | DataModelFromSchemaDefinition, 15 | DocumentByName, 16 | TableNamesInDataModel, 17 | SystemTableNames, 18 | } from "convex/server"; 19 | import type { GenericId } from "convex/values"; 20 | import schema from "../schema.js"; 21 | 22 | /** 23 | * The names of all of your Convex tables. 24 | */ 25 | export type TableNames = TableNamesInDataModel; 26 | 27 | /** 28 | * The type of a document stored in Convex. 29 | * 30 | * @typeParam TableName - A string literal type of the table name (like "users"). 31 | */ 32 | export type Doc = DocumentByName< 33 | DataModel, 34 | TableName 35 | >; 36 | 37 | /** 38 | * An identifier for a document in Convex. 39 | * 40 | * Convex documents are uniquely identified by their `Id`, which is accessible 41 | * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids). 42 | * 43 | * Documents can be loaded using `db.get(id)` in query and mutation functions. 44 | * 45 | * IDs are just strings at runtime, but this type can be used to distinguish them from other 46 | * strings when type checking. 47 | * 48 | * @typeParam TableName - A string literal type of the table name (like "users"). 49 | */ 50 | export type Id = 51 | GenericId; 52 | 53 | /** 54 | * A type describing your Convex data model. 55 | * 56 | * This type includes information about what tables you have, the type of 57 | * documents stored in those tables, and the indexes defined on them. 58 | * 59 | * This type is used to parameterize methods like `queryGeneric` and 60 | * `mutationGeneric` to make them type-safe. 61 | */ 62 | export type DataModel = DataModelFromSchemaDefinition; 63 | 64 | /* prettier-ignore-end */ 65 | -------------------------------------------------------------------------------- /convex/_generated/server.d.ts: -------------------------------------------------------------------------------- 1 | /* prettier-ignore-start */ 2 | 3 | /* eslint-disable */ 4 | /** 5 | * Generated utilities for implementing server-side Convex query and mutation functions. 6 | * 7 | * THIS CODE IS AUTOMATICALLY GENERATED. 8 | * 9 | * To regenerate, run `npx convex dev`. 10 | * @module 11 | */ 12 | 13 | import { 14 | ActionBuilder, 15 | HttpActionBuilder, 16 | MutationBuilder, 17 | QueryBuilder, 18 | GenericActionCtx, 19 | GenericMutationCtx, 20 | GenericQueryCtx, 21 | GenericDatabaseReader, 22 | GenericDatabaseWriter, 23 | } from "convex/server"; 24 | import type { DataModel } from "./dataModel.js"; 25 | 26 | /** 27 | * Define a query in this Convex app's public API. 28 | * 29 | * This function will be allowed to read your Convex database and will be accessible from the client. 30 | * 31 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument. 32 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible. 33 | */ 34 | export declare const query: QueryBuilder; 35 | 36 | /** 37 | * Define a query that is only accessible from other Convex functions (but not from the client). 38 | * 39 | * This function will be allowed to read from your Convex database. It will not be accessible from the client. 40 | * 41 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument. 42 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible. 43 | */ 44 | export declare const internalQuery: QueryBuilder; 45 | 46 | /** 47 | * Define a mutation in this Convex app's public API. 48 | * 49 | * This function will be allowed to modify your Convex database and will be accessible from the client. 50 | * 51 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. 52 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. 53 | */ 54 | export declare const mutation: MutationBuilder; 55 | 56 | /** 57 | * Define a mutation that is only accessible from other Convex functions (but not from the client). 58 | * 59 | * This function will be allowed to modify your Convex database. It will not be accessible from the client. 60 | * 61 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. 62 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. 63 | */ 64 | export declare const internalMutation: MutationBuilder; 65 | 66 | /** 67 | * Define an action in this Convex app's public API. 68 | * 69 | * An action is a function which can execute any JavaScript code, including non-deterministic 70 | * code and code with side-effects, like calling third-party services. 71 | * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. 72 | * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. 73 | * 74 | * @param func - The action. It receives an {@link ActionCtx} as its first argument. 75 | * @returns The wrapped action. Include this as an `export` to name it and make it accessible. 76 | */ 77 | export declare const action: ActionBuilder; 78 | 79 | /** 80 | * Define an action that is only accessible from other Convex functions (but not from the client). 81 | * 82 | * @param func - The function. It receives an {@link ActionCtx} as its first argument. 83 | * @returns The wrapped function. Include this as an `export` to name it and make it accessible. 84 | */ 85 | export declare const internalAction: ActionBuilder; 86 | 87 | /** 88 | * Define an HTTP action. 89 | * 90 | * This function will be used to respond to HTTP requests received by a Convex 91 | * deployment if the requests matches the path and method where this action 92 | * is routed. Be sure to route your action in `convex/http.js`. 93 | * 94 | * @param func - The function. It receives an {@link ActionCtx} as its first argument. 95 | * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up. 96 | */ 97 | export declare const httpAction: HttpActionBuilder; 98 | 99 | /** 100 | * A set of services for use within Convex query functions. 101 | * 102 | * The query context is passed as the first argument to any Convex query 103 | * function run on the server. 104 | * 105 | * This differs from the {@link MutationCtx} because all of the services are 106 | * read-only. 107 | */ 108 | export type QueryCtx = GenericQueryCtx; 109 | 110 | /** 111 | * A set of services for use within Convex mutation functions. 112 | * 113 | * The mutation context is passed as the first argument to any Convex mutation 114 | * function run on the server. 115 | */ 116 | export type MutationCtx = GenericMutationCtx; 117 | 118 | /** 119 | * A set of services for use within Convex action functions. 120 | * 121 | * The action context is passed as the first argument to any Convex action 122 | * function run on the server. 123 | */ 124 | export type ActionCtx = GenericActionCtx; 125 | 126 | /** 127 | * An interface to read from the database within Convex query functions. 128 | * 129 | * The two entry points are {@link DatabaseReader.get}, which fetches a single 130 | * document by its {@link Id}, or {@link DatabaseReader.query}, which starts 131 | * building a query. 132 | */ 133 | export type DatabaseReader = GenericDatabaseReader; 134 | 135 | /** 136 | * An interface to read from and write to the database within Convex mutation 137 | * functions. 138 | * 139 | * Convex guarantees that all writes within a single mutation are 140 | * executed atomically, so you never have to worry about partial writes leaving 141 | * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control) 142 | * for the guarantees Convex provides your functions. 143 | */ 144 | export type DatabaseWriter = GenericDatabaseWriter; 145 | 146 | /* prettier-ignore-end */ 147 | -------------------------------------------------------------------------------- /convex/_generated/server.js: -------------------------------------------------------------------------------- 1 | /* prettier-ignore-start */ 2 | 3 | /* eslint-disable */ 4 | /** 5 | * Generated utilities for implementing server-side Convex query and mutation functions. 6 | * 7 | * THIS CODE IS AUTOMATICALLY GENERATED. 8 | * 9 | * To regenerate, run `npx convex dev`. 10 | * @module 11 | */ 12 | 13 | import { 14 | actionGeneric, 15 | httpActionGeneric, 16 | queryGeneric, 17 | mutationGeneric, 18 | internalActionGeneric, 19 | internalMutationGeneric, 20 | internalQueryGeneric, 21 | } from "convex/server"; 22 | 23 | /** 24 | * Define a query in this Convex app's public API. 25 | * 26 | * This function will be allowed to read your Convex database and will be accessible from the client. 27 | * 28 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument. 29 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible. 30 | */ 31 | export const query = queryGeneric; 32 | 33 | /** 34 | * Define a query that is only accessible from other Convex functions (but not from the client). 35 | * 36 | * This function will be allowed to read from your Convex database. It will not be accessible from the client. 37 | * 38 | * @param func - The query function. It receives a {@link QueryCtx} as its first argument. 39 | * @returns The wrapped query. Include this as an `export` to name it and make it accessible. 40 | */ 41 | export const internalQuery = internalQueryGeneric; 42 | 43 | /** 44 | * Define a mutation in this Convex app's public API. 45 | * 46 | * This function will be allowed to modify your Convex database and will be accessible from the client. 47 | * 48 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. 49 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. 50 | */ 51 | export const mutation = mutationGeneric; 52 | 53 | /** 54 | * Define a mutation that is only accessible from other Convex functions (but not from the client). 55 | * 56 | * This function will be allowed to modify your Convex database. It will not be accessible from the client. 57 | * 58 | * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. 59 | * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. 60 | */ 61 | export const internalMutation = internalMutationGeneric; 62 | 63 | /** 64 | * Define an action in this Convex app's public API. 65 | * 66 | * An action is a function which can execute any JavaScript code, including non-deterministic 67 | * code and code with side-effects, like calling third-party services. 68 | * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. 69 | * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. 70 | * 71 | * @param func - The action. It receives an {@link ActionCtx} as its first argument. 72 | * @returns The wrapped action. Include this as an `export` to name it and make it accessible. 73 | */ 74 | export const action = actionGeneric; 75 | 76 | /** 77 | * Define an action that is only accessible from other Convex functions (but not from the client). 78 | * 79 | * @param func - The function. It receives an {@link ActionCtx} as its first argument. 80 | * @returns The wrapped function. Include this as an `export` to name it and make it accessible. 81 | */ 82 | export const internalAction = internalActionGeneric; 83 | 84 | /** 85 | * Define a Convex HTTP action. 86 | * 87 | * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object 88 | * as its second. 89 | * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`. 90 | */ 91 | export const httpAction = httpActionGeneric; 92 | 93 | /* prettier-ignore-end */ 94 | -------------------------------------------------------------------------------- /convex/auth.config.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | providers: [ 3 | { 4 | domain: process.env.CONVEX_SITE_URL, 5 | applicationID: "convex", 6 | }, 7 | ], 8 | }; 9 | -------------------------------------------------------------------------------- /convex/auth.ts: -------------------------------------------------------------------------------- 1 | import GitHub from "@auth/core/providers/github"; 2 | import Resend from "@auth/core/providers/resend"; 3 | import { convexAuth } from "@convex-dev/auth/server"; 4 | 5 | export const { auth, signIn, signOut, store } = convexAuth({ 6 | providers: [GitHub, Resend], 7 | callbacks: { 8 | async redirect(params) { 9 | console.log(params); 10 | if (!params.redirectTo) { 11 | if (!process.env.SITE_URL) { 12 | throw new Error("SITE_URL is not set"); 13 | } 14 | return process.env.SITE_URL; 15 | } 16 | const url = new URL(params.redirectTo); 17 | if ( 18 | [ 19 | new URL(process.env.SITE_URL || process.env.CONVEX_SITE_URL!) 20 | .hostname, 21 | "localhost", 22 | "www.convex-cms.com", 23 | "vite.convex-cms.com", 24 | "tanstack.convex-cms.com", 25 | "convex-cms.com", 26 | "labs.convex.dev", 27 | ].includes(url.hostname) 28 | ) { 29 | return params.redirectTo; 30 | } 31 | throw new Error("Invalid redirect URL"); 32 | // return process.env.SITE_URL; 33 | }, 34 | }, 35 | }); 36 | -------------------------------------------------------------------------------- /convex/crons.ts: -------------------------------------------------------------------------------- 1 | import { cronJobs } from "convex/server"; 2 | import { internal } from "./_generated/api"; 3 | 4 | const crons = cronJobs(); 5 | 6 | crons.daily( 7 | "Reset all tables to initial dataset", 8 | { hourUTC: 7, minuteUTC: 0 }, 9 | internal.data.reset, 10 | ); 11 | 12 | export default crons; 13 | -------------------------------------------------------------------------------- /convex/data.ts: -------------------------------------------------------------------------------- 1 | import { internalMutation } from "./_generated/server"; 2 | import type { Id, TableNames } from "./_generated/dataModel"; 3 | import { byEmail, getOrSetSlug } from "./users"; 4 | 5 | const USERS = ["ian@convex.dev", "wayne@convex.dev", "contact@anjana.dev"]; 6 | const POSTS = [ 7 | { 8 | authorIndex: 1, 9 | content: `A few months into their startup journey, Emily and Jason had successfully launched their platform, thanks to the robust backend support from Convex.dev. Their users loved the smooth, intuitive experience, and the team was ready to take the next big step: adding content management capabilities. 10 | 11 | When Convex announced their new CMS feature, Emily and Jason were thrilled. The CMS was exactly what they needed to empower their users to manage their content seamlessly within the platform. The developers spent the day exploring the new feature, diving into its functionalities, and brainstorming how they could integrate it to enhance their platform’s offerings. 12 | 13 | The creative startup office buzzed with excitement as they mapped out new possibilities. Jason pointed out key features on the laptop screen while Emily jotted down implementation ideas. The large screen in the office displayed the CMS dashboard, hinting at the powerful new tools they were eager to incorporate. This new addition to Convex’s offerings not only fueled their excitement but also opened up a world of possibilities for their startup’s growth.`, 14 | imageUrl: 15 | "https://pleasant-albatross-666.convex.cloud/api/storage/82027b58-1979-435c-a41a-e55205b0a0c5", 16 | published: true, 17 | slug: "convexcms", 18 | summary: 19 | "This new addition to Convex’s offerings not only fueled their excitement but also opened up a world of possibilities for their startup’s growth.", 20 | title: "Exploring Convex’s New CMS", 21 | }, 22 | { 23 | authorIndex: 0, 24 | title: "Introducing Convex Auth", 25 | slug: "introducing-convex-auth", 26 | summary: 27 | "Convex Auth is a library for implementing authentication natively in your Convex backend.", 28 | published: true, 29 | content: ` "Convex Auth is a library for implementing authentication using your Convex backend. 30 | 31 | Check it out [in the Convex docs 32 | ](https: //docs.convex.dev/auth/convex-auth) to get started or play with the [example demo](https://labs.convex.dev/auth-example) ([source](https://github.com/get-convex/convex-auth-example)). 33 | 34 | *This article is based on the [launch video 35 | ](https: //convex.dev/auth).* 36 | 37 | # Motivation 38 | 39 | Convex is designed for building multi-user applications. And if your app has users, it needs authentication. But authentication is a really complex component of a full-stack app. For this reason we have been recommending the built-in integrations with mature authentication platforms like [Clerk 40 | ](https: //clerk.dev/) and [Auth0](https://auth0.com/). 41 | 42 | Yet many developers have been asking for a self-hosted solution. The auth platforms I mentioned have a ton of features but they also store the authentication data. This complicates your app, as that data has to be somehow synced or shared with your backend and database. 43 | 44 | ![diagram of client convex and auth server 45 | ](https: //cdn.sanity.io/images/ts10onj4/production/d0c8eae535ad0c9dc4bc2bfe336a7d3d5c3553cc-2798x1476.png) 46 | 47 | This is a surmountable challenge, but maybe you’re just getting started and your app doesn’t need every authentication feature. You’d rather have more control over the data and a simpler architecture to build on top of. 48 | 49 | ![diagram of client and convex server 50 | ](https: //cdn.sanity.io/images/ts10onj4/production/c8226a4d784f83be8bb5b7d569fe422bfdac838c-1957x805.png) 51 | 52 | # Functionality 53 | 54 | Convex Auth enables you to build such a solution. It is inspired by the excellent [Auth.js 55 | ](https: //authjs.dev/) and [Lucia](https://lucia-auth.com/) libraries, and reuses some of their implementation. It is also similar in its capabilities to auth solutions such as Firebase Auth and Supabase Auth (although it doesn’t have all of their features yet). 56 | 57 | In the [demo 58 | ](https: //labs.convex.dev/auth-example) you can see the various sign-in methods you can implement with Convex Auth. It supports sign-in via OAuth, magic links, one-time-passwords and normal email and password combination. You can use any of the 80 OAuth providers supported by Auth.js. 59 | 60 | # Code deep dive 61 | 62 | ## Server configuration 63 | 64 | The main configuration file is \`auth.ts\` in your convex directory, which configures the available authentication methods: 65 | 66 | \`\`\`jsx 67 | import GitHub from '@auth/core/providers/github'; 68 | import Google from '@auth/core/providers/google'; 69 | import Resend from '@auth/core/providers/resend'; 70 | import { Password 71 | } from '@convex-dev/auth/providers/Password'; 72 | 73 | export const { auth, signIn, signOut, store 74 | } = convexAuth({ 75 | providers: [GitHub, Google, Resend, Password 76 | ], 77 | }); 78 | \`\`\` 79 | 80 | Your \`schema.ts\` must also include the tables used by the library, including the \`users\` table. This is because the library uses indexes on these tables for efficient lookups: 81 | 82 | \`\`\`jsx 83 | import { authTables 84 | } from '@convex-dev/auth/server'; 85 | import { defineSchema, defineTable 86 | } from 'convex/server'; 87 | import { v 88 | } from 'convex/values'; 89 | 90 | export default defineSchema({ 91 | ...authTables, 92 | // Your other tables... 93 | }); 94 | \`\`\` 95 | 96 | There is additional configuration in \`auth.config.ts\` and \`https.ts\`, but you won’t need to touch these. See [Manual Setup 97 | ](https: //labs.convex.dev/auth/setup/manual) for more details if you’re interested. 98 | 99 | ## Frontend configuration 100 | 101 | On the frontend, instead of using \`ConvexProvider\`, the app is wrapped in \`ConvexAuthProvider\`. Then in the \`App\` root component, the \`Authenticated\` and \`Unauthenticated\` components (from \`convex/react\`) are used to render different UI based on the authentication state. When not authenticated, your app can render the sign-in form: 102 | 103 | \`\`\`jsx 104 | import { Content 105 | } from '@/Content'; 106 | import { SignInForm 107 | } from '@/auth/SignInForm'; 108 | import { Authenticated, Unauthenticated 109 | } from 'convex/react'; 110 | 111 | export default function App() { 112 | return ( 113 | <> 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | ); 122 | } 123 | 124 | \`\`\` 125 | 126 | The key part of the sign-in UI is calling the \`signIn\` function with the name of one of the authentication methods configured in \`auth.ts\`. For example here’s a form that sends the user a magic link: 127 | 128 | \`\`\`jsx 129 | 130 | import { useAuthActions 131 | } from '@convex-dev/auth/react'; 132 | 133 | export function SignInWithMagicLink() { 134 | const { signIn 135 | } = useAuthActions(); 136 | return ( 137 |
{ 140 | event.preventDefault(); 141 | const formData = new FormData(event.currentTarget); 142 | void signIn('resend', formData); 143 | } 144 | } 145 | > 146 | 147 | 148 | 149 |
150 | ); 151 | } 152 | \`\`\` 153 | 154 | ## Handling authentication 155 | 156 | Finally, let’s look at how the authentication state is used to power the signed-in experience. The \`auth.ts\` file exports an \`auth\` helper, which has methods for retrieving the current user and session ID. Using these methods, we can return the information about the current user back to the client: 157 | 158 | \`\`\`jsx 159 | import { query 160 | } from './_generated/server'; 161 | import { auth 162 | } from './auth'; 163 | 164 | export const viewer = query({ 165 | args: {}, 166 | handler: async (ctx) => { 167 | const userId = await auth.getUserId(ctx); 168 | return userId !== null ? ctx.db.get(userId) : null; 169 | }, 170 | }); 171 | \`\`\` 172 | 173 | As well as enforce that certain functions can only be called by signed-in users: 174 | 175 | \`\`\`jsx 176 | import { query, mutation 177 | } from './_generated/server'; 178 | import { v 179 | } from 'convex/values'; 180 | import { auth 181 | } from './auth'; 182 | 183 | export const send = mutation({ 184 | args: { body: v.string() 185 | }, 186 | handler: async (ctx, 187 | { body 188 | }) => { 189 | const userId = await auth.getUserId(ctx); 190 | if (userId === null) { 191 | throw new Error('Not signed in'); 192 | } 193 | // Send a new message. 194 | await ctx.db.insert('messages', 195 | { body, userId 196 | }); 197 | }, 198 | }); 199 | \`\`\` 200 | 201 | ## Conclusion 202 | 203 | And that’s all it takes to get self-hosted auth to work. From here I recommend you read through the [docs 204 | ](https: //labs.convex.dev/auth). They go into detail on how to implement the various authentication methods and on the trade-offs between them. I hope you’ll find the library useful. Please let us know what you think on our [discord](https://arc.net/l/quote/dxljwnkc)." 205 | `, 206 | }, 207 | { 208 | authorIndex: 1, 209 | content: `A team of full-stack developers, comprised of Alex, Priya, and Mateo, were always on the lookout for new tools and technologies that could push the boundaries of their projects. When they heard about the Convex “Zero to One” hackathon, they decided to join, eager to explore what this new backend platform could offer. 210 | 211 | The hackathon challenge was simple yet ambitious: build something unique using Convex.dev in just 48 hours. The team brainstormed and decided to create a blog platform that could effortlessly handle dynamic content and user interactions. They were drawn to Convex’s promise of fast, scalable, and serverless backend solutions, which seemed perfect for their idea. 212 | 213 | As they delved into the development, they were impressed by how quickly they could set up their backend using Convex. The platform’s real-time features and seamless integration with their frontend frameworks allowed them to focus on creating a rich, interactive user experience without worrying about managing servers or databases. The project came together faster than they expected, with Convex handling the heavy lifting behind the scenes. 214 | 215 | By the end of the hackathon, their blog platform was not only functional but also robust and scalable. The experience had been so smooth and empowering that they decided to take their idea further. The team transformed their hackathon project into a full-fledged startup, using Convex as the backbone of their platform. They envisioned expanding the blog into a community-driven space where users could create, share, and interact with content effortlessly. 216 | 217 | With Convex.dev, they were confident they could scale their startup quickly and efficiently. What started as a hackathon experiment had now evolved into a startup venture, fueled by the possibilities that Convex unlocked for them. The journey from zero to one was just the beginning, and they were excited to see where Convex would take them next.`, 218 | imageUrl: 219 | "https://pleasant-albatross-666.convex.cloud/api/storage/6a651783-cb93-4878-a7c9-784091e560c4", 220 | published: true, 221 | slug: "hackathon-startup", 222 | summary: 223 | "With Convex.dev, they were confident they could scale their startup quickly and efficiently. ", 224 | title: "From Hackathon to Startup with Convex", 225 | }, 226 | { 227 | authorIndex: 2, 228 | content: `Two full-stack developers, Emily and Jason, were deep into building their startup, an innovative platform aimed at simplifying online event management. They had been struggling with the backend infrastructure, trying to find a solution that would allow them to focus more on the frontend and less on managing complex databases and APIs. 229 | 230 | One day, Emily stumbled upon Convex.dev while researching backend solutions. Excited, she immediately shared it with Jason. They were both impressed by how Convex.dev promised to simplify their workflow by providing a fully managed backend platform that integrated seamlessly with their preferred frontend frameworks. The speed and ease of use were exactly what they needed to accelerate their development process. They could now build, test, and deploy features faster, giving them more time to focus on their startup’s unique value proposition. 231 | 232 | In their sleek, modern office, Emily and Jason dove into Convex.dev, quickly realizing how it could transform their project. The whiteboard behind them was soon filled with new ideas and plans, as they excitedly mapped out the next steps for their startup, now confident that they had the right tools to bring their vision to life.`, 233 | imageUrl: 234 | "https://pleasant-albatross-666.convex.cloud/api/storage/19ead46b-c4d6-47df-bd3f-ff007761c6c0", 235 | published: true, 236 | slug: "discovering-convex", 237 | summary: 238 | "Two full-stack developers, Emily and Jason, were deep into building their startup, an innovative platform aimed at simplifying online event management. ", 239 | title: "Discovering Convex.dev", 240 | }, 241 | ]; 242 | 243 | export const clearPosts = internalMutation({ 244 | args: {}, 245 | handler: async (ctx) => { 246 | await Promise.all( 247 | ["posts", "versions"].map(async (table) => { 248 | const oldData = await ctx.db.query(table as TableNames).collect(); 249 | await Promise.all( 250 | oldData.map(async ({ _id }) => { 251 | await ctx.db.delete(_id); 252 | }), 253 | ); 254 | console.log( 255 | `Deleted ${oldData.length} documents from "${table}" table`, 256 | ); 257 | }), 258 | ); 259 | }, 260 | }); 261 | 262 | export const reset = internalMutation({ 263 | args: {}, 264 | handler: async (ctx) => { 265 | await clearPosts(ctx, {}); 266 | const userIds: Id<"users">[] = await Promise.all( 267 | USERS.map(async (email) => { 268 | const user = await byEmail(ctx, { email }); 269 | if (!user) throw new Error("user not found " + email); 270 | console.log(`Found ${user._id} in "users" table`); 271 | const slug = await getOrSetSlug(ctx, { id: user._id }); 272 | console.log(`Author slug: ${slug}`); 273 | return user._id; 274 | }), 275 | ); 276 | await Promise.all( 277 | POSTS.map(async (p) => { 278 | const { authorIndex, ...post } = p; 279 | const authorId = userIds[authorIndex]; 280 | const { title, content, summary, slug } = post; 281 | const search = [title, content, summary, slug].join(" "); 282 | 283 | const postId = await ctx.db.insert("posts", { 284 | ...post, 285 | authorId, 286 | publishTime: Date.now(), 287 | search, 288 | }); 289 | console.log(`Created document ${postId} in "posts" table`); 290 | const versionId = await ctx.db.insert("versions", { 291 | ...post, 292 | postId, 293 | authorId, 294 | editorId: authorId, 295 | }); 296 | console.log(`Created document ${versionId} in "versions" table`); 297 | }), 298 | ); 299 | }, 300 | }); 301 | -------------------------------------------------------------------------------- /convex/http.ts: -------------------------------------------------------------------------------- 1 | import { httpRouter } from "convex/server"; 2 | import { auth } from "./auth"; 3 | import { httpAction } from "./_generated/server"; 4 | 5 | const http = httpRouter(); 6 | 7 | auth.addHttpRoutes(http); 8 | 9 | http.route({ 10 | pathPrefix: "/", 11 | method: "GET", 12 | handler: httpAction(async (_, request) => { 13 | const { 14 | body: { storageId }, 15 | } = await request.json(); 16 | 17 | console.log(`received request.url ${request.url}`); 18 | console.log(`received request.body.storageId ${storageId}`); 19 | 20 | return new Response(null, { 21 | status: 200, 22 | }); 23 | }), 24 | }); 25 | 26 | export default http; 27 | -------------------------------------------------------------------------------- /convex/images.ts: -------------------------------------------------------------------------------- 1 | import { 2 | query, 3 | mutation, 4 | internalMutation, 5 | internalQuery, 6 | } from "./_generated/server"; 7 | import { viewer as getViewer } from "./users"; 8 | import schema from "./schema"; 9 | import { omit } from "convex-helpers"; 10 | import { crud } from "convex-helpers/server/crud"; 11 | import { internal } from "./_generated/api"; 12 | import { v } from "convex/values"; 13 | 14 | export const { read, update } = crud( 15 | schema, 16 | "images", 17 | internalQuery, 18 | internalMutation, 19 | ); 20 | 21 | export const getUrl = query({ 22 | args: { id: v.id("images") }, 23 | handler: async (ctx, args) => { 24 | return (await ctx.db.get(args.id))?.url; 25 | }, 26 | }); 27 | 28 | export const generateUploadUrl = mutation({ 29 | args: {}, 30 | handler: async (ctx) => { 31 | // Verify the user is authenticated 32 | const viewer = await getViewer(ctx, {}); 33 | if (!viewer) 34 | throw new Error("User not authenticated; cannot generate upload URL"); 35 | 36 | // Return an upload URL 37 | return await ctx.storage.generateUploadUrl(); 38 | }, 39 | }); 40 | 41 | const imageFields = schema.tables.images.validator.fields; 42 | export const saveOptimized = mutation({ 43 | args: omit(imageFields, ["url"]), 44 | handler: async (ctx, args) => { 45 | // Verify the user is still authenticated 46 | const viewer = await getViewer(ctx, {}); 47 | if (!viewer) throw new Error("User not authenticated; cannot save file"); 48 | 49 | // Save the original file metadata & storageId to 'images' table 50 | const url = await ctx.storage.getUrl(args.storageId); 51 | if (!url) throw new Error(`No url found for storageId ${args.storageId}`); 52 | const imageId = await ctx.db.insert("images", { ...args, url }); 53 | 54 | // Trigger the optimizeAndSave action 55 | await ctx.scheduler.runAfter(0, internal.sharp.convertAndUpdate, { 56 | imageId, 57 | }); 58 | return (await ctx.db.get(imageId))!; 59 | }, 60 | }); 61 | 62 | export const save = mutation({ 63 | args: omit(imageFields, ["url"]), 64 | handler: async (ctx, args) => { 65 | // Verify the user is still authenticated 66 | const viewer = await getViewer(ctx, {}); 67 | if (!viewer) throw new Error("User not authenticated; cannot save file"); 68 | 69 | // Get the URL 70 | const url = await ctx.storage.getUrl(args.storageId); 71 | if (!url) throw new Error(`No url found for storageId ${args.storageId}`); 72 | 73 | // Save the file metadata, url & storageId to 'images' table 74 | const docId = await ctx.db.insert("images", { ...args, url }); 75 | return (await ctx.db.get(docId))!; 76 | }, 77 | }); 78 | -------------------------------------------------------------------------------- /convex/posts.ts: -------------------------------------------------------------------------------- 1 | import { v } from "convex/values"; 2 | import { mutation as rawMutation, query } from "./_generated/server"; 3 | import schema from "./schema"; 4 | import { Triggers } from "convex-helpers/server/triggers"; 5 | import { DataModel, type Doc } from "./_generated/dataModel"; 6 | import { 7 | customMutation, 8 | customCtx, 9 | } from "convex-helpers/server/customFunctions"; 10 | 11 | // Use Triggers to keep aggregated 'search' field up-to-date 12 | // by automatically updating it whenever a post is created/updated. 13 | // See also: https://stack.convex.dev/triggers#denormalizing-a-field 14 | const triggers = new Triggers(); 15 | 16 | triggers.register("posts", async (ctx, change) => { 17 | console.log("Triggered on posts with change: ", change); 18 | if (change.newDoc) { 19 | // A post has been inserted or updated; 20 | // aggregate the relevant searchable text fields 21 | // into a single 'search' string to be indexed 22 | const { title, content, summary, slug } = change.newDoc; 23 | const newSearch = [title, content, summary, slug].join(" "); 24 | 25 | // if the search aggregate has changed, update it 26 | if (change.newDoc.search !== newSearch) { 27 | console.log( 28 | `Triggering search field update for ${slug} (post ${change.id})`, 29 | ); 30 | await ctx.db.patch(change.id, { search: newSearch }); 31 | } 32 | } 33 | }); 34 | // Wrap the default Convex mutation function to be aware of our trigger 35 | const mutation = customMutation(rawMutation, customCtx(triggers.wrapDB)); 36 | 37 | export const publish = mutation({ 38 | args: { 39 | versionId: v.id("versions"), 40 | }, 41 | handler: async (ctx, args) => { 42 | const version = await ctx.db.get(args.versionId); 43 | if (!version) { 44 | throw new Error(`Version ${args.versionId} not found`); 45 | } 46 | const { 47 | _id, 48 | _creationTime, 49 | editorId: _editorId, 50 | postId, 51 | ...content 52 | } = version; 53 | const oldPost = await ctx.db.get(postId); 54 | 55 | if (!oldPost) { 56 | throw new Error(`Post ${version.postId} not found`); 57 | } 58 | const patch = { 59 | ...content, 60 | published: true, 61 | publishTime: oldPost.publishTime || Date.now(), 62 | updateTime: Date.now(), 63 | }; 64 | await ctx.db.patch(postId, patch); 65 | return ctx.db.get(postId); 66 | }, 67 | }); 68 | 69 | export const list = query({ 70 | args: {}, 71 | handler: async (ctx) => { 72 | // If the user is authenticated, include unpublished drafts 73 | // by omitting the index filter. Otherwise, use the index 74 | // filter to only return published posts 75 | const authed = await ctx.auth.getUserIdentity(); 76 | 77 | const posts = await ctx.db 78 | .query("posts") 79 | .withIndex( 80 | "by_published", 81 | authed ? undefined : (q) => q.eq("published", true), 82 | ) 83 | .order("desc") 84 | .collect(); 85 | 86 | return Promise.all( 87 | posts.map(async (post) => { 88 | // Add the author's details to each post. 89 | const author = (await ctx.db.get(post.authorId))!; 90 | return { ...post, author }; 91 | }), 92 | ); 93 | }, 94 | }); 95 | 96 | export const getById = query({ 97 | args: { 98 | id: v.id("posts"), 99 | withAuthor: v.optional(v.boolean()), 100 | }, 101 | handler: async (ctx, args) => { 102 | const { id, withAuthor } = args; 103 | const post = await ctx.db.get(id); 104 | if (!post) return null; 105 | let author; 106 | if (withAuthor) { 107 | // Add the author's details to each post. 108 | author = (await ctx.db.get(post.authorId))!; 109 | } 110 | return { ...post, author }; 111 | }, 112 | }); 113 | 114 | type PostAugmented = Doc<"posts"> & { 115 | publicVersion?: Doc<"versions">; 116 | draft?: Doc<"versions">; 117 | author?: Doc<"users">; 118 | }; 119 | export const getBySlug = query({ 120 | args: { 121 | slug: v.string(), 122 | withDraft: v.optional(v.boolean()), 123 | withAuthor: v.optional(v.boolean()), 124 | }, 125 | handler: async (ctx, args) => { 126 | const versionsBySlug = ctx.db 127 | .query("versions") 128 | .withIndex("by_slug", (q) => q.eq("slug", args.slug)); 129 | 130 | const publicVersion = await versionsBySlug 131 | .filter((q) => q.eq(q.field("published"), true)) 132 | .order("desc") 133 | .first(); 134 | 135 | let post = await ctx.db 136 | .query("posts") 137 | .withIndex("by_slug", (q) => q.eq("slug", args.slug)) 138 | .order("desc") 139 | .first(); 140 | 141 | if (!post) { 142 | // The slug for this post may have changed 143 | // try searching for this slug in old versions 144 | if (publicVersion) { 145 | // The slug is outdated, lookup the postId 146 | post = await ctx.db.get(publicVersion.postId); 147 | } 148 | } 149 | if (!post) return null; // The slug is unknown 150 | 151 | const authed = await ctx.auth.getUserIdentity(); 152 | if (!authed && !post.published) { 153 | // This is an unpublished draft, unauthenticated 154 | // user does not have permission to view it 155 | return null; 156 | } 157 | 158 | const result: PostAugmented = post; 159 | if (publicVersion) { 160 | result.publicVersion = publicVersion; 161 | } 162 | 163 | if (args.withDraft) { 164 | // Find the most recent unpublished draft, if any, 165 | // created after this post was last updated 166 | const draft = await ctx.db 167 | .query("versions") 168 | .withIndex("by_postId", (q) => q.eq("postId", post._id)) 169 | .filter((q) => 170 | q.and( 171 | q.gt( 172 | q.field("_creationTime"), 173 | post.updateTime || post._creationTime, 174 | ), 175 | q.eq(q.field("published"), false), 176 | ), 177 | ) 178 | .order("desc") 179 | .first(); 180 | if (draft) { 181 | result.draft = draft; 182 | } 183 | } 184 | 185 | if (args.withAuthor) { 186 | const author = await ctx.db.get(post.authorId); 187 | if (author) { 188 | result.author = author; 189 | } 190 | } 191 | 192 | return result; 193 | }, 194 | }); 195 | 196 | export const isSlugTaken = query({ 197 | args: { 198 | slug: v.string(), 199 | postId: schema.tables.posts.validator.fields.postId, 200 | }, 201 | handler: async (ctx, args) => { 202 | const { slug, postId } = args; 203 | 204 | // Find any existing post(s) with this slug and flag 205 | // any whose postId doesn't match the one given 206 | const posts = await ctx.db 207 | .query("posts") 208 | .withIndex("by_slug", (q) => q.eq("slug", slug)) 209 | .collect(); 210 | const badPostIds = new Set( 211 | posts.filter((p) => p._id !== postId).map((p) => p._id), 212 | ); 213 | 214 | // It's possible that the slug is no longer in use on any posts, 215 | // but had previously been used in an old version of another post. 216 | // Collect all version(s) with this slug... 217 | const versions = await ctx.db 218 | .query("versions") 219 | .withIndex("by_slug", (q) => q.eq("slug", slug)) 220 | .collect(); 221 | // ...and flag any whose postId doesn't match the one given. 222 | const badVersions = versions.filter((v) => v.postId !== postId); 223 | badVersions.map((v) => badPostIds.add(v.postId)); 224 | 225 | if (badPostIds.size > 0) { 226 | // This slug is unavailable (already/previously in use) 227 | const msg = `Slug "${slug}" is unavailable, used on post(s) ${Array.from(badPostIds).toString()}`; 228 | console.error(msg); 229 | return msg; 230 | } else { 231 | return false; 232 | } 233 | }, 234 | }); 235 | 236 | export const search = query({ 237 | args: { searchTerm: v.string() }, 238 | handler: async (ctx, args) => { 239 | const authed = await ctx.auth.getUserIdentity(); 240 | 241 | const results = await ctx.db 242 | .query("posts") 243 | .withSearchIndex("search_all", (q) => { 244 | const search = q.search("search", args.searchTerm); 245 | 246 | // Search public + draft posts if user is authed; 247 | // otherwise, add filter to only search public posts 248 | return authed ? search : search.eq("published", true); 249 | }) 250 | .collect(); 251 | 252 | return Promise.all( 253 | results.map(async (post) => { 254 | // Add the author's details to each post. 255 | const author = (await ctx.db.get(post.authorId))!; 256 | return { ...post, author }; 257 | }), 258 | ); 259 | }, 260 | }); 261 | -------------------------------------------------------------------------------- /convex/schema.ts: -------------------------------------------------------------------------------- 1 | import { defineSchema, defineTable } from "convex/server"; 2 | import { authTables } from "@convex-dev/auth/server"; 3 | import { z, type ZodString } from "zod"; 4 | import { zid, zodToConvexFields } from "convex-helpers/server/zod"; 5 | 6 | //// Zod validation helpers //// 7 | const required = { required_error: "Required" }; 8 | export const slugRegEx = /^(\w+)((-\w+)+)?$/; 9 | export const zodSlug = z 10 | .string(required) 11 | .regex( 12 | slugRegEx, 13 | "Slug can only contain letters, numbers, hyphens or underscores", 14 | ); 15 | // Accept empty strings in addition to undefined for form validation 16 | export const zodOptionalString = (zs?: ZodString) => 17 | z.optional(z.union([z.literal(""), zs || z.string()])); 18 | const zodOptionalUrl = zodOptionalString(z.string().url()); 19 | 20 | //// Content schema & Validation //// 21 | 22 | // When a new post is created, we add a new `posts` document. 23 | // To track version history, each time a post is edited 24 | // (published or not) we add a new `versions` document with the 25 | // edited content, adding metadata like editorId. 26 | // When a version is (un)published, we update the `posts` document 27 | // with the given version content, and metadata like the publishTime. 28 | export const postContentZod = { 29 | title: z.string(required).min(2).max(60), 30 | slug: zodSlug, 31 | summary: zodOptionalString( 32 | z.string().min(10, "10 characters min").max(200, "200 characters max"), 33 | ), 34 | content: z.string(), 35 | imageUrl: zodOptionalUrl, 36 | authorId: zid("users"), 37 | published: z.boolean(), 38 | search: zodOptionalString(), // aggregates all searchable fields 39 | }; 40 | export const postsZod = { 41 | ...postContentZod, 42 | publishTime: z.optional(z.number()), 43 | updateTime: z.optional(z.number()), 44 | // deprecated 45 | postId: zodOptionalString(), 46 | }; 47 | 48 | export const versionsZod = { 49 | ...postContentZod, 50 | postId: zid("posts"), 51 | editorId: zid("users"), 52 | }; 53 | 54 | export const usersZod = { 55 | image: zodOptionalUrl, 56 | url: zodOptionalUrl, 57 | tagline: zodOptionalString(z.string().max(100, "100 characters max")), 58 | bio: zodOptionalString(z.string().max(500, "500 characters max")), 59 | name: zodOptionalString(), 60 | slug: zodOptionalString(), 61 | email: zodOptionalString(z.string().email()), 62 | emailVerificationTime: z.optional(z.number()), 63 | phone: zodOptionalString(), 64 | phoneVerificationTime: z.optional(z.number()), 65 | isAnonymous: z.optional(z.boolean()), 66 | // deprecated 67 | userId: z.optional(zid("users")), 68 | }; 69 | 70 | export const imagesZod = { 71 | name: zodOptionalString(), 72 | storageId: zid("_storage"), 73 | url: z.string().url(), 74 | type: zodOptionalString(), 75 | size: z.optional(z.number()), 76 | }; 77 | 78 | //// Convex DB //// 79 | export default defineSchema({ 80 | ...authTables, 81 | users: defineTable(zodToConvexFields(usersZod)).index("email", ["email"]), 82 | posts: defineTable(zodToConvexFields(postsZod)) 83 | .index("by_slug", ["slug"]) 84 | .index("by_published", ["published", "publishTime", "updateTime"]) 85 | .index("by_authorId", ["authorId"]) 86 | .searchIndex("search_all", { 87 | searchField: "search", 88 | filterFields: ["published"], 89 | }), 90 | versions: defineTable(zodToConvexFields(versionsZod)) 91 | .index("by_postId", ["postId"]) 92 | .index("by_slug", ["slug"]), // to lookup old slugs for redirects 93 | images: defineTable(zodToConvexFields(imagesZod)).index("by_storageID", [ 94 | "storageId", 95 | ]), 96 | }); 97 | -------------------------------------------------------------------------------- /convex/sharp.ts: -------------------------------------------------------------------------------- 1 | "use node"; 2 | 3 | import sharp from "sharp"; 4 | import { v } from "convex/values"; 5 | import { internalAction } from "./_generated/server"; 6 | import { internal } from "./_generated/api"; 7 | 8 | export const convertAndUpdate = internalAction({ 9 | args: { 10 | imageId: v.id("images"), 11 | width: v.optional(v.number()), 12 | }, 13 | handler: async (ctx, args) => { 14 | const { imageId, width } = args; 15 | const image = await ctx.runQuery(internal.images.read, { id: imageId }); 16 | if (!image) throw new Error(`Image not found: ${imageId}`); 17 | 18 | const original = await ctx.storage.get(image.storageId); 19 | if (original === null) 20 | throw new Error(`Storage ID not found: ${image.storageId}`); 21 | 22 | const buffer = await original.arrayBuffer(); 23 | 24 | let sharped = sharp(buffer); 25 | if (width) { 26 | sharped = sharped.resize(width); 27 | } 28 | const webp = await sharped.webp().toBuffer(); 29 | const type = "image/webp"; 30 | const blob = new Blob([webp], { type }); 31 | 32 | const convertedId = await ctx.storage.store(blob); 33 | const convertedUrl = await ctx.storage.getUrl(convertedId); 34 | if (!convertedUrl) 35 | throw new Error(`No url found for storageId ${convertedId}`); 36 | 37 | const oldName = image.name || `Image_${imageId}`; 38 | const newName = oldName + `_w${width}.webp`; 39 | 40 | await ctx.runMutation(internal.images.update, { 41 | id: imageId, 42 | patch: { 43 | storageId: convertedId, 44 | type, 45 | name: newName, 46 | size: blob.size, 47 | url: convertedUrl, 48 | }, 49 | }); 50 | }, 51 | }); 52 | -------------------------------------------------------------------------------- /convex/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | /* This TypeScript project config describes the environment that 3 | * Convex functions run in and is used to typecheck them. 4 | * You can modify it, but some settings required to use Convex. 5 | */ 6 | "compilerOptions": { 7 | /* These settings are not required by Convex and can be modified. */ 8 | "allowJs": true, 9 | "strict": true, 10 | "moduleResolution": "Bundler", 11 | "jsx": "react-jsx", 12 | "skipLibCheck": true, 13 | "allowSyntheticDefaultImports": true, 14 | /* These compiler options are required by Convex */ 15 | "target": "ESNext", 16 | "lib": ["ES2021", "dom"], 17 | "forceConsistentCasingInFileNames": true, 18 | "module": "ESNext", 19 | "isolatedModules": true, 20 | "noEmit": true 21 | }, 22 | "include": ["./**/*"], 23 | "exclude": ["./_generated"] 24 | } 25 | -------------------------------------------------------------------------------- /convex/users.ts: -------------------------------------------------------------------------------- 1 | import { v } from "convex/values"; 2 | import { query, mutation } from "./_generated/server"; 3 | import { auth } from "./auth"; 4 | import schema from "./schema"; 5 | import { partial } from "convex-helpers/validators"; 6 | 7 | export const update = mutation({ 8 | args: { 9 | id: v.id("users"), 10 | patch: v.object(partial(schema.tables.users.validator.fields)), 11 | }, 12 | handler: async (ctx, args) => { 13 | const userId = await auth.getUserId(ctx); 14 | if (!userId) throw new Error("User not authenticated"); 15 | await ctx.db.patch(args.id, args.patch); 16 | }, 17 | }); 18 | 19 | export const viewer = query({ 20 | args: {}, 21 | handler: async (ctx) => { 22 | const userId = await auth.getUserId(ctx); 23 | return userId ? await ctx.db.get(userId) : null; 24 | }, 25 | }); 26 | 27 | export const authoredPosts = query({ 28 | args: { userId: v.id("users") }, 29 | handler: async (ctx, args) => { 30 | return await ctx.db 31 | .query("posts") 32 | .withIndex("by_authorId", (q) => q.eq("authorId", args.userId)) 33 | .collect(); 34 | }, 35 | }); 36 | 37 | export const listAuthors = query({ 38 | args: {}, 39 | handler: async (ctx) => { 40 | const users = await ctx.db.query("users").collect(); 41 | const withPosts = await Promise.all( 42 | users.map(async (u) => { 43 | const posts = await authoredPosts(ctx, { userId: u._id }); 44 | return posts.length ? { ...u, posts } : null; 45 | }), 46 | ); 47 | return withPosts.filter((u) => !!u); 48 | }, 49 | }); 50 | 51 | export const byEmail = query({ 52 | args: { 53 | email: v.string(), 54 | }, 55 | handler: async (ctx, args) => { 56 | return await ctx.db 57 | .query("users") 58 | .filter((q) => q.eq(q.field("email"), args.email)) 59 | .unique(); 60 | }, 61 | }); 62 | 63 | export const getOrSetSlug = mutation({ 64 | args: { id: v.id("users") }, 65 | handler: async (ctx, args) => { 66 | const user = await ctx.db.get(args.id); 67 | if (user === null) return null; 68 | if (user.slug) return user.slug; 69 | 70 | let slug; 71 | if (user.name) { 72 | slug = encodeURIComponent(user.name.toLowerCase().replaceAll(" ", "-")); 73 | } else if (user.email) { 74 | slug = encodeURIComponent(user.email); 75 | } else { 76 | slug = user._id; 77 | } 78 | await ctx.db.patch(user._id, { slug }); 79 | return slug; 80 | }, 81 | }); 82 | 83 | export const bySlug = query({ 84 | args: { slug: v.string() }, 85 | handler: async (ctx, args) => { 86 | return await ctx.db 87 | .query("users") 88 | .filter((q) => q.eq(q.field("slug"), args.slug)) 89 | .unique(); 90 | }, 91 | }); 92 | -------------------------------------------------------------------------------- /convex/versions.ts: -------------------------------------------------------------------------------- 1 | import { v } from "convex/values"; 2 | import { mutation, query, type QueryCtx } from "./_generated/server"; 3 | import type { Doc } from "./_generated/dataModel"; 4 | import { isSlugTaken } from "./posts"; 5 | import schema from "./schema"; 6 | 7 | export const saveDraft = mutation({ 8 | args: { 9 | ...schema.tables.versions.validator.fields, 10 | postId: v.optional(v.union(v.literal(""), v.id("posts"))), 11 | }, 12 | handler: async (ctx, args) => { 13 | const { postId, editorId, ...data } = args; 14 | const slugTaken = await isSlugTaken(ctx, { 15 | slug: data.slug, 16 | postId: postId || undefined, 17 | }); 18 | if (slugTaken) throw new Error(slugTaken); 19 | 20 | let id = postId; 21 | if (!id) { 22 | id = await ctx.db.insert("posts", data); 23 | } 24 | return (await ctx.db.get( 25 | await ctx.db.insert("versions", { ...data, editorId, postId: id }), 26 | ))!; 27 | }, 28 | }); 29 | 30 | const joinUsers = async (ctx: QueryCtx, version: Doc<"versions">) => { 31 | const author = (await ctx.db.get(version.authorId))!; 32 | const editor = (await ctx.db.get(version.editorId))!; 33 | return { ...version, author, editor }; 34 | }; 35 | 36 | export const getById = query({ 37 | args: { 38 | versionId: v.id("versions"), 39 | withUsers: v.optional(v.boolean()), 40 | }, 41 | handler: async (ctx, args) => { 42 | const version = await ctx.db.get(args.versionId); 43 | if (!version) return null; 44 | return args.withUsers ? await joinUsers(ctx, version) : version; 45 | }, 46 | }); 47 | 48 | export const getPostHistory = query({ 49 | args: { 50 | postId: v.id("posts"), 51 | }, 52 | handler: async (ctx, args) => { 53 | const versions = await ctx.db 54 | .query("versions") 55 | .withIndex("by_postId", (q) => q.eq("postId", args.postId)) 56 | .order("desc") 57 | .collect(); 58 | 59 | const withUsers = await Promise.all(versions.map((v) => joinUsers(ctx, v))); 60 | return withUsers; 61 | }, 62 | }); 63 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 36 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | Convex CMS Template 45 | 46 | 47 | 48 |
49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "convex-cms-vite", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "npm-run-all --parallel dev:frontend dev:backend", 8 | "dev:frontend": "vite --open", 9 | "dev:backend": "convex dev", 10 | "predev": "convex dev --until-success", 11 | "build": "tsc -b && vite build", 12 | "lint": "tsc && eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", 13 | "preview": "vite preview" 14 | }, 15 | "dependencies": { 16 | "@auth/core": "^0.34.1", 17 | "@convex-dev/auth": "^0.0.32", 18 | "@hookform/resolvers": "^3.9.0", 19 | "@radix-ui/react-dialog": "^1.0.5", 20 | "@radix-ui/react-dropdown-menu": "^2.0.6", 21 | "@radix-ui/react-icons": "^1.3.0", 22 | "@radix-ui/react-label": "^2.1.0", 23 | "@radix-ui/react-scroll-area": "^1.1.0", 24 | "@radix-ui/react-slot": "^1.1.0", 25 | "@radix-ui/react-switch": "^1.1.0", 26 | "@radix-ui/react-toast": "^1.2.1", 27 | "@radix-ui/react-toggle": "^1.0.3", 28 | "@radix-ui/react-toggle-group": "^1.0.4", 29 | "@xixixao/uploadstuff": "^0.0.5", 30 | "class-variance-authority": "^0.7.0", 31 | "clsx": "^2.1.1", 32 | "convex": "^1.13.0", 33 | "convex-helpers": "^0.1.60", 34 | "next-themes": "^0.3.0", 35 | "react": "^18.3.1", 36 | "react-dom": "^18.3.1", 37 | "react-hook-form": "^7.52.2", 38 | "react-markdown": "^9.0.1", 39 | "react-router": "^6.26.0", 40 | "react-router-dom": "^6.26.0", 41 | "rehype-highlight": "^7.0.0", 42 | "remark-gfm": "^4.0.0", 43 | "sharp": "^0.33.5", 44 | "tailwind-merge": "^2.3.0", 45 | "tailwindcss-animate": "^1.0.7", 46 | "zod": "^3.23.8" 47 | }, 48 | "devDependencies": { 49 | "@tailwindcss/typography": "^0.5.13", 50 | "@types/node": "^20.14.9", 51 | "@types/react": "^18.3.3", 52 | "@types/react-dom": "^18.3.0", 53 | "@typescript-eslint/eslint-plugin": "^7.13.1", 54 | "@typescript-eslint/parser": "^7.13.1", 55 | "@vitejs/plugin-react": "^4.3.1", 56 | "autoprefixer": "^10.4.19", 57 | "dotenv": "^16.4.5", 58 | "eslint": "^8.57.0", 59 | "eslint-plugin-react-hooks": "^4.6.2", 60 | "eslint-plugin-react-refresh": "^0.4.7", 61 | "npm-run-all": "^4.1.5", 62 | "postcss": "^8.4.39", 63 | "prettier": "3.3.2", 64 | "tailwindcss": "^3.4.4", 65 | "typescript": "^5.2.2", 66 | "vite": "^5.3.1", 67 | "vite-plugin-pages": "^0.32.3" 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /public/assets/convex.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /setup.mjs: -------------------------------------------------------------------------------- 1 | /** 2 | * This script runs `npx @convex-dev/auth` to help with setting up 3 | * environment variables for Convex Auth. 4 | * 5 | * You can safely delete it and remove it from package.json scripts. 6 | */ 7 | 8 | import fs from "fs"; 9 | import { config as loadEnvFile } from "dotenv"; 10 | import { spawnSync } from "child_process"; 11 | 12 | if (!fs.existsSync(".env.local")) { 13 | // Something is off, skip the script. 14 | process.exit(0); 15 | } 16 | 17 | const config = {}; 18 | loadEnvFile({ path: ".env.local", processEnv: config }); 19 | 20 | const runOnceWorkflow = process.argv.includes("--once"); 21 | 22 | if (runOnceWorkflow && config.SETUP_SCRIPT_RAN !== undefined) { 23 | // The script has already ran once, skip. 24 | process.exit(0); 25 | } 26 | 27 | // The fallback should never be used. 28 | const deploymentName = 29 | config.CONVEX_DEPLOYMENT.split(":").slice(-1)[0] ?? ""; 30 | 31 | const variables = JSON.stringify({ 32 | help: 33 | "This template includes prebuilt sign-in via GitHub OAuth and " + 34 | "magic links via Resend. " + 35 | "This command can help you configure the credentials for these services " + 36 | "via additional Convex environment variables.", 37 | providers: [ 38 | { 39 | name: "GitHub OAuth", 40 | help: 41 | "Create a GitHub OAuth App, follow the instruction here: " + 42 | "https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app\n\n" + 43 | `When you're asked for a callback URL use:\n\n` + 44 | ` https://${deploymentName}.convex.site/api/auth/callback/github`, 45 | variables: [ 46 | { 47 | name: "AUTH_GITHUB_ID", 48 | description: "the Client ID of your GitHub OAuth App", 49 | }, 50 | { 51 | name: "AUTH_GITHUB_SECRET", 52 | description: "the generated client secret", 53 | }, 54 | ], 55 | }, 56 | { 57 | name: "Resend", 58 | help: "Sign up for Resend at https://resend.com/signup. Then create an API Key.", 59 | variables: [ 60 | { 61 | name: "AUTH_RESEND_KEY", 62 | description: "the API Key", 63 | }, 64 | ], 65 | }, 66 | ], 67 | success: 68 | "You're all set. If you need to, you can rerun this command with `node setup.mjs`.", 69 | }); 70 | 71 | console.error( 72 | "You chose Convex Auth as the auth solution. " + 73 | "This command will walk you through setting up " + 74 | "the required Convex environment variables", 75 | ); 76 | 77 | const result = spawnSync( 78 | "npx", 79 | ["@convex-dev/auth", "--variables", variables, "--skip-git-check"], 80 | { stdio: "inherit" }, 81 | ); 82 | 83 | if (runOnceWorkflow) { 84 | fs.writeFileSync(".env.local", `\nSETUP_SCRIPT_RAN=1\n`, { flag: "a" }); 85 | } 86 | 87 | process.exit(result.status); 88 | -------------------------------------------------------------------------------- /src/components/Author/Edit.tsx: -------------------------------------------------------------------------------- 1 | import { useMutation } from "convex/react"; 2 | import { api } from "../../../convex/_generated/api"; 3 | import { zodResolver } from "@hookform/resolvers/zod"; 4 | import { Label } from "@/components/ui/label"; 5 | import { Switch } from "@/components/ui/switch"; 6 | import { Form } from "@/components/ui/form"; 7 | import { useState, type FormEventHandler } from "react"; 8 | import { useForm, type SubmitHandler } from "react-hook-form"; 9 | import { useNavigate } from "react-router-dom"; 10 | import { z } from "zod"; 11 | import { Toolbar } from "@/components/Toolbar"; 12 | import { TextField, MarkdownField } from "@/components/Inputs"; 13 | import { Button } from "@/components/ui/button"; 14 | import { useToast } from "@/components/ui/use-toast"; 15 | import type { Doc } from "../../../convex/_generated/dataModel"; 16 | import { usersZod } from "../../../convex/schema"; 17 | import { AuthorProfile } from "./Profile"; 18 | 19 | export function EditableProfile({ user }: { user: Doc<"users"> }) { 20 | const { toast } = useToast(); 21 | const navigate = useNavigate(); 22 | 23 | const [previewing, setPreviewing] = useState(false); 24 | 25 | const update = useMutation(api.users.update); 26 | 27 | const zodSchema = z.object(usersZod); 28 | const defaultValues = user; 29 | 30 | const form = useForm>({ 31 | defaultValues, 32 | resolver: zodResolver(zodSchema), 33 | }); 34 | 35 | const onReset = () => { 36 | form.reset(defaultValues); 37 | navigate(`/authors/${user._id}`); 38 | }; 39 | 40 | const onSubmit: SubmitHandler> = async (data) => { 41 | try { 42 | await update({ id: user._id, patch: data }); 43 | toast({ 44 | title: "User Profile Updated", 45 | }); 46 | form.reset(data); 47 | navigate(`/authors/${user._id}`); 48 | } catch (e) { 49 | const error = e as Error; 50 | toast({ 51 | variant: "destructive", 52 | title: "Error Updating Profile", 53 | description: error.message, 54 | }); 55 | } 56 | }; 57 | 58 | // Wrapper for form.handleSubmit to avoid no-misused-promises error; 59 | // see https://github.com/orgs/react-hook-form/discussions/8020 60 | const submitHandler: FormEventHandler = (...args) => 61 | void form.handleSubmit(onSubmit)(...args); 62 | 63 | const { isValid, isDirty } = form.formState; 64 | const values = form.getValues(); 65 | 66 | return ( 67 | <> 68 | 69 |
70 |
71 | setPreviewing(checked)} 75 | /> 76 | 77 |
78 | 79 |
80 | 83 | 84 | 87 |
88 |
89 |
90 |
91 | {previewing ? ( 92 | 93 | ) : ( 94 |
95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | )} 106 |
107 | 108 | ); 109 | } 110 | -------------------------------------------------------------------------------- /src/components/Author/Profile.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | AvatarIcon, 3 | EnvelopeClosedIcon, 4 | GlobeIcon, 5 | } from "@radix-ui/react-icons"; 6 | import type { Doc } from "../../../convex/_generated/dataModel"; 7 | import { Link } from "react-router-dom"; 8 | import { StyledContent, StyledMarkdown } from "../Markdown"; 9 | import { PreviewGallery } from "../Blog/Post"; 10 | import { PageTitle } from "../PageTitle"; 11 | 12 | const sizeClass = { 13 | s: `h-5 w-5`, 14 | m: `h-10 w-10`, 15 | l: `h-24 w-24`, 16 | full: `h-full w-full`, 17 | }; 18 | 19 | export function UserImage({ 20 | src, 21 | size, 22 | }: { 23 | src?: string; 24 | size?: keyof typeof sizeClass; 25 | }) { 26 | if (src) { 27 | return ( 28 | Profile image 33 | ); 34 | } else { 35 | return ; 36 | } 37 | } 38 | 39 | export function CompactProfile({ user }: { user: Doc<"users"> }) { 40 | return ( 41 | 45 | 46 |
47 |

{user.name || `User ${user._id}`}

48 | {user.tagline && } 49 |
50 | 51 | ); 52 | } 53 | 54 | export function AuthorProfile({ 55 | user, 56 | posts, 57 | }: { 58 | user: Doc<"users">; 59 | posts?: Doc<"posts">[]; 60 | }) { 61 | return ( 62 |
63 |
64 | 65 |
66 | 67 | {user.tagline && } 68 | 69 |
70 | {user.url && ( 71 | 76 | 77 | {user.url.replace(/http(s?):\/\//, "")} 78 | 79 | )} 80 | {user.email && ( 81 | 85 | 86 | {user.email} 87 | 88 | )} 89 |
90 |
91 |
92 |
93 | {user.bio && } 94 | {posts && ( 95 |
96 |

97 | Posts by this author 98 |

99 | 100 |
101 | )} 102 |
103 | ); 104 | } 105 | 106 | export function AuthorsList({ users }: { users: Doc<"users">[] }) { 107 | return ( 108 |
109 | {users.map((u) => ( 110 | 111 | ))} 112 |
113 | ); 114 | } 115 | -------------------------------------------------------------------------------- /src/components/Blog/Edit.tsx: -------------------------------------------------------------------------------- 1 | import { useMutation, useQuery } from "convex/react"; 2 | import { api } from "../../../convex/_generated/api"; 3 | import { useEffect, useState, type FormEventHandler } from "react"; 4 | import { ImageField, MarkdownField, TextField } from "@/components/Inputs"; 5 | import { Button } from "@/components/ui/button"; 6 | import { versionsZod } from "../../../convex/schema"; 7 | import { useForm, type SubmitHandler } from "react-hook-form"; 8 | import { z } from "zod"; 9 | import { zodResolver } from "@hookform/resolvers/zod"; 10 | import { useToast } from "@/components/ui/use-toast"; 11 | import { Form } from "@/components/ui/form"; 12 | import { Switch } from "@/components/ui/switch"; 13 | import { Label } from "../ui/label"; 14 | import { DisplayPost, type PostOrVersion } from "./Post"; 15 | import { useNavigate, useSearchParams } from "react-router-dom"; 16 | import { VersionHistory } from "@/components/Blog/History"; 17 | import { Toolbar } from "../Toolbar"; 18 | import type { Doc } from "../../../convex/_generated/dataModel"; 19 | 20 | const versionDefaults = { 21 | postId: "", 22 | slug: "", 23 | title: "", 24 | summary: "", 25 | content: "", 26 | imageUrl: "", 27 | authorId: "", 28 | editorId: "", 29 | published: false, 30 | }; 31 | 32 | export function EditablePost({ version }: { version: Doc<"versions"> | null }) { 33 | const { toast } = useToast(); 34 | const navigate = useNavigate(); 35 | const [_, setSearchParams] = useSearchParams(); 36 | 37 | const [previewing, setPreviewing] = useState(false); 38 | 39 | const viewer = useQuery(api.users.viewer); 40 | 41 | const saveDraft = useMutation(api.versions.saveDraft); 42 | const publishPost = useMutation(api.posts.publish); 43 | 44 | const zodSchema = z.object({ ...versionsZod, image: z.any() }); 45 | type Schema = z.infer; 46 | 47 | const defaultValues = version || versionDefaults; 48 | 49 | const form = useForm({ 50 | defaultValues, 51 | resolver: zodResolver(zodSchema), 52 | }); 53 | 54 | const { getValues, setValue, setError } = form; 55 | 56 | const slugTaken = useQuery( 57 | api.posts.isSlugTaken, 58 | getValues("slug") 59 | ? { 60 | slug: getValues("slug"), 61 | postId: getValues("postId"), 62 | } 63 | : "skip", 64 | ); 65 | 66 | useEffect(() => { 67 | if (slugTaken) { 68 | setError("slug", { message: "Slug already in use" }); 69 | } 70 | }, [slugTaken, setError]); 71 | 72 | useEffect(() => { 73 | if (viewer) { 74 | if (!getValues("authorId") && viewer) { 75 | setValue("authorId", viewer._id); 76 | } 77 | setValue("editorId", viewer._id); 78 | } 79 | }, [viewer, getValues, setValue]); 80 | 81 | const onSaveDraft: SubmitHandler = async (data) => { 82 | try { 83 | const newVersion = await saveDraft({ 84 | ...data, 85 | published: false, 86 | }); 87 | if (!newVersion) throw new Error("Error saving draft"); 88 | 89 | toast({ 90 | title: "Draft saved", 91 | description: `Saved new draft version ${newVersion._id}. This draft is not published yet.`, 92 | }); 93 | 94 | if (newVersion.slug !== version?.slug) { 95 | navigate(`/${newVersion.slug}/edit?v=${newVersion._id}`); 96 | } else { 97 | setSearchParams((params) => ({ ...params, v: newVersion._id })); 98 | } 99 | } catch (e) { 100 | const error = e as Error; 101 | toast({ 102 | variant: "destructive", 103 | title: "Error saving draft", 104 | description: error.message, 105 | }); 106 | } 107 | }; 108 | 109 | const onPublish: SubmitHandler = async (data) => { 110 | try { 111 | const newVersion = await saveDraft({ ...data, published: true }); 112 | if (!newVersion) throw new Error("Error saving version"); 113 | 114 | const updatedPost = await publishPost({ 115 | versionId: newVersion._id, 116 | }); 117 | if (!updatedPost) throw new Error("Error publishing post"); 118 | 119 | toast({ 120 | title: "Post published", 121 | description: `Published version ${newVersion._id} of post ${updatedPost._id}`, 122 | }); 123 | form.reset(data); 124 | navigate(`/${newVersion.slug}`); 125 | } catch (e) { 126 | const error = e as Error; 127 | toast({ 128 | variant: "destructive", 129 | title: "Error publishing post", 130 | description: error.message, 131 | }); 132 | } 133 | }; 134 | 135 | // Wrapper for form.handleSubmit to avoid no-misused-promises error; 136 | // see https://github.com/orgs/react-hook-form/discussions/8020 137 | const getSubmitHandler = function ( 138 | handler: SubmitHandler, 139 | ): FormEventHandler { 140 | return (...args) => void form.handleSubmit(handler)(...args); 141 | }; 142 | 143 | const { isValid, isDirty } = form.formState; 144 | 145 | return ( 146 | <> 147 | 148 |
149 |
150 |
151 | setPreviewing(checked)} 155 | /> 156 | 159 |
160 | 161 | {version && ( 162 | 167 | )} 168 |
169 | 170 |
173 | 184 | 185 | 193 | 194 | 201 |
202 |
203 |
204 | 205 | {previewing ? ( 206 |
207 | 210 |
211 | ) : ( 212 |
213 | 214 |
215 | 216 | 217 | 218 | 219 | 220 |
221 |
222 | 223 | )} 224 | 225 | ); 226 | } 227 | -------------------------------------------------------------------------------- /src/components/Blog/History.tsx: -------------------------------------------------------------------------------- 1 | import { ArrowRightIcon, ClockIcon, ReloadIcon } from "@radix-ui/react-icons"; 2 | import { useQuery } from "convex/react"; 3 | import { api } from "../../../convex/_generated/api"; 4 | import { ScrollArea } from "@/components/ui/scroll-area"; 5 | import type { Doc, Id } from "../../../convex/_generated/dataModel"; 6 | import { showTimeAgo } from "@/lib/utils"; 7 | import { Button } from "../ui/button"; 8 | import { 9 | DropdownMenu, 10 | DropdownMenuContent, 11 | DropdownMenuItem, 12 | DropdownMenuLabel, 13 | DropdownMenuSeparator, 14 | DropdownMenuTrigger, 15 | } from "@/components/ui/dropdown-menu"; 16 | import { useSearchParams } from "react-router-dom"; 17 | import { useToast } from "../ui/use-toast"; 18 | 19 | export function VersionHistory({ 20 | postId, 21 | currentVersion, 22 | isDirty, 23 | }: { 24 | postId: Id<"posts">; 25 | currentVersion: Id<"versions">; 26 | isDirty: boolean; 27 | }) { 28 | const { toast } = useToast(); 29 | const [_, setSearchParams] = useSearchParams(); 30 | 31 | const history = useQuery(api.versions.getPostHistory, { postId }); 32 | const totalCount = history?.length; 33 | 34 | const restoreVersion = (id: Id<"versions">) => { 35 | if (isDirty) { 36 | return toast({ 37 | title: "Cannot restore history with unsaved edits.", 38 | description: 39 | "You have unsaved edits. Save or discard your changes before restoring.", 40 | variant: "destructive", 41 | }); 42 | } 43 | setSearchParams((params) => ({ ...params, v: id })); 44 | toast({ 45 | title: `Now editing version ${id}`, 46 | description: `Publish to restore this version, or edit and save as a new version`, 47 | }); 48 | }; 49 | 50 | return ( 51 | 52 | 53 | 60 | 61 | 62 | 63 | {totalCount 64 | ? `${totalCount} Version${totalCount === 1 ? "" : "s"}` 65 | : "Version History"} 66 | 67 | 68 | 69 | {history?.map((v) => ( 70 | restoreVersion(v._id)} 75 | /> 76 | ))} 77 | 78 | 79 | 80 | ); 81 | } 82 | 83 | function HistoryDropdownItem({ 84 | version, 85 | selected, 86 | onRestore, 87 | }: { 88 | version: Doc<"versions"> & { editor: Doc<"users">; author: Doc<"users"> }; 89 | selected: boolean; 90 | onRestore: () => void; 91 | }) { 92 | const { _id, _creationTime } = version; 93 | const created = new Date(_creationTime).toUTCString(); 94 | const ago = showTimeAgo(_creationTime); 95 | 96 | const viewing = selected 97 | ? "Currently viewing this version" 98 | : "Click to restore this version"; 99 | const details = `${version.editor.name} edited at ${created}`; 100 | 101 | return ( 102 | 107 | 116 | 117 | ); 118 | } 119 | -------------------------------------------------------------------------------- /src/components/Blog/Post.tsx: -------------------------------------------------------------------------------- 1 | import { PageTitle } from "../PageTitle"; 2 | import { StyledMarkdown } from "../Markdown"; 3 | import { Link } from "react-router-dom"; 4 | import { UserImage } from "../Author/Profile"; 5 | import type { Id, Doc } from "../../../convex/_generated/dataModel"; 6 | import { FileTextIcon } from "@radix-ui/react-icons"; 7 | 8 | export type PostWithAuthor = Doc<"posts"> & { 9 | author?: Doc<"users">; 10 | }; 11 | 12 | // Either a `posts` or `versions` document, or unsaved version 13 | export type PostOrVersion = Doc<"posts"> & 14 | Doc<"versions"> & { 15 | _id?: Id<"posts"> | Id<"versions">; 16 | editorId?: Id<"users"> | null; 17 | postId?: Id<"posts">; 18 | author?: Doc<"users"> | null; 19 | }; 20 | 21 | export function Byline({ 22 | author, 23 | timestamp, 24 | }: { 25 | author: Doc<"users"> | null; 26 | timestamp?: number; 27 | }) { 28 | // If no timestamp given, this is a draft/preview; show today's date 29 | const date = new Date(timestamp || Date.now()).toDateString(); 30 | 31 | return ( 32 | author && ( 33 |
34 | 35 |
36 | 40 | {author.name} 41 | 42 |
{date}
43 |
44 |
45 | ) 46 | ); 47 | } 48 | 49 | export function PostImage({ 50 | imageUrl, 51 | title, 52 | }: Partial>) { 53 | if (imageUrl) { 54 | return ( 55 | {`Cover 60 | ); 61 | } else { 62 | return ( 63 |
64 | 65 |
66 | ); 67 | } 68 | } 69 | 70 | export function PostPreview({ post }: { post: PostWithAuthor }) { 71 | return ( 72 | post && ( 73 |
78 | 79 |
80 |
81 |
82 |
83 | {post.title} 84 |
85 | {post.summary && ( 86 |
87 | 88 |
89 | )} 90 |
91 |
92 | {post.author && ( 93 | 94 | )} 95 |
96 |
97 | ) 98 | ); 99 | } 100 | 101 | export function PreviewGallery({ posts }: { posts: Doc<"posts">[] }) { 102 | if (!posts?.length) { 103 | return ( 104 |

105 | No posts found 106 |

107 | ); 108 | } else { 109 | return ( 110 |
111 | {posts?.map((post) => )} 112 |
113 | ); 114 | } 115 | } 116 | 117 | export function DisplayPost({ post }: { post: PostOrVersion }) { 118 | return ( 119 | post && ( 120 |
121 |
122 |
123 | 124 | {post.author && ( 125 | 126 | )} 127 | 128 | {post.summary && ( 129 |
130 | 131 |
132 | )} 133 |
134 |
135 | {post.imageUrl && ( 136 | 137 | )} 138 |
139 | 140 |
141 | 142 |
143 |
144 |
145 | ) 146 | ); 147 | } 148 | -------------------------------------------------------------------------------- /src/components/Code.tsx: -------------------------------------------------------------------------------- 1 | import { ReactNode } from "react"; 2 | 3 | export const Code = ({ children }: { children: ReactNode }) => { 4 | return ( 5 | 6 | {children} 7 | 8 | ); 9 | }; 10 | -------------------------------------------------------------------------------- /src/components/GetStarted/ConvexLogo.tsx: -------------------------------------------------------------------------------- 1 | export const ConvexLogo = ({ 2 | width, 3 | height, 4 | }: { 5 | width?: number; 6 | height?: number; 7 | }) => ( 8 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | ); 27 | -------------------------------------------------------------------------------- /src/components/GetStarted/GetStartedDialog.tsx: -------------------------------------------------------------------------------- 1 | import { ConvexLogo } from "@/components/GetStarted/ConvexLogo"; 2 | import { Code } from "@/components/Code"; 3 | import { Button } from "@/components/ui/button"; 4 | import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; 5 | import { 6 | Dialog, 7 | DialogClose, 8 | DialogContent, 9 | DialogFooter, 10 | DialogHeader, 11 | DialogTitle, 12 | DialogTrigger, 13 | } from "@/components/ui/dialog"; 14 | import { 15 | CodeIcon, 16 | ExternalLinkIcon, 17 | MagicWandIcon, 18 | StackIcon, 19 | } from "@radix-ui/react-icons"; 20 | import { ReactNode } from "react"; 21 | 22 | export function GetStartedDialog({ children }: { children: ReactNode }) { 23 | return ( 24 | 25 | {children} 26 | 27 | 28 | 29 | Your app powered by 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | ); 41 | } 42 | 43 | export function GetStartedContent() { 44 | return ( 45 |
46 |

47 | This template is a starting point for building your content-driven 48 | fullstack web application. 49 |

50 |

51 | To prevent abuse, the content in the public demo app hosted at{" "} 52 | 57 | convex-cms.com 58 | {" "} 59 | is reset daily using a Convex{" "} 60 | 65 | cron job 66 | {" "} 67 | defined in convex/crons.ts. You can edit & create new 68 | posts, but your changes will be deleted within 24 hours. 69 |

70 |

Explore the code

71 |
72 | 73 | 74 | 75 | Inspect the database 76 | 77 | 78 | 79 | Open the{" "} 80 | 85 | Convex dashboard 86 | {" "} 87 | in another window. 88 | 89 | 90 | 91 | 92 | 93 | 94 | Change the backend 95 | 96 | 97 | 98 | Edit the functions in the convex/ directory to change 99 | the backend functionality. 100 | 101 | 102 | 103 | 104 | 105 | 106 | Change the frontend 107 | 108 | 109 | 110 | Edit src/components and src/pages to 111 | change your frontend. 112 | 113 | 114 |
115 |
116 |

Helpful resources

117 |
118 | 119 | Read comprehensive documentation for all Convex features. 120 | 121 | 122 | Learn about best practices, use cases, and more from a growing 123 | collection of articles, videos, and walkthroughs. 124 | 125 | 126 | Join our developer community to ask questions, trade tips & tricks, 127 | and show off your projects. 128 | 129 | 130 | Get unblocked quickly by searching across the docs, Stack, and 131 | Discord chats. 132 | 133 |
134 |
135 |
136 | ); 137 | } 138 | 139 | function Resource({ 140 | title, 141 | children, 142 | href, 143 | }: { 144 | title: string; 145 | children: ReactNode; 146 | href: string; 147 | }) { 148 | return ( 149 | 162 | ); 163 | } 164 | -------------------------------------------------------------------------------- /src/components/Inputs.tsx: -------------------------------------------------------------------------------- 1 | import { Input } from "./ui/input"; 2 | import type { 3 | FieldPath, 4 | FieldValue, 5 | FieldValues, 6 | UseFormReturn, 7 | } from "react-hook-form"; 8 | import { 9 | FormField, 10 | FormItem, 11 | FormLabel, 12 | FormControl, 13 | FormMessage, 14 | FormDescription, 15 | } from "./ui/form"; 16 | import { Textarea } from "./ui/textarea"; 17 | import { useMutation, useQuery } from "convex/react"; 18 | import { api } from "../../convex/_generated/api"; 19 | import { 20 | UploadButton, 21 | type UploadFileResponse, 22 | } from "@xixixao/uploadstuff/react"; 23 | import "@xixixao/uploadstuff/react/styles.css"; 24 | import type { Id } from "../../convex/_generated/dataModel"; 25 | import { useToast } from "./ui/use-toast"; 26 | import { useEffect, useState } from "react"; 27 | 28 | interface CommonProps { 29 | name: FieldPath; 30 | form: UseFormReturn; 31 | } 32 | 33 | interface TextFieldProps 34 | extends CommonProps { 35 | hidden?: boolean; 36 | required?: boolean; 37 | itemClass?: string; 38 | controlClass?: string; 39 | } 40 | 41 | export function TextField({ 42 | name, 43 | form, 44 | hidden, 45 | required, 46 | itemClass, 47 | controlClass, 48 | }: TextFieldProps) { 49 | const ifRequired = required ? { required: true, "aria-required": true } : {}; 50 | return ( 51 | ( 55 | 58 |
59 | 60 | {name} 61 | {required && "*"} 62 | 63 | 64 |
65 | 66 | void form.trigger()} 70 | {...ifRequired} 71 | /> 72 | 73 |
74 | )} 75 | /> 76 | ); 77 | } 78 | 79 | interface MarkdownFieldProps 80 | extends TextFieldProps { 81 | rows?: number; 82 | } 83 | 84 | export function MarkdownField({ 85 | name, 86 | form, 87 | rows, 88 | required, 89 | }: MarkdownFieldProps) { 90 | const ifRequired = required ? { required: true, "aria-required": true } : {}; 91 | return ( 92 | ( 96 | 97 |
98 | 99 | {name} 100 | {required && "*"} 101 | 102 | Markdown allowed 103 | 104 |
105 | 106 |