Repository: sudomf/remix-vite Branch: main Commit: 4beedae0def2 Files: 92 Total size: 110.9 KB Directory structure: gitextract_mjw2yo5y/ ├── .eslintignore ├── .gitattributes ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.yaml │ │ └── feature_request.yaml │ ├── PULL_REQUEST_TEMPLATE/ │ │ └── default.md │ └── workflows/ │ └── publish.yml ├── .gitignore ├── .npmrc ├── .prettierignore ├── LICENSE ├── README.md ├── config/ │ └── husky/ │ └── pre-commit ├── examples/ │ ├── complex/ │ │ ├── .dockerignore │ │ ├── .eslintrc.js │ │ ├── .gitignore │ │ ├── .gitpod.Dockerfile │ │ ├── .gitpod.yml │ │ ├── .npmrc │ │ ├── .prettierignore │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── app/ │ │ │ ├── db.server.ts │ │ │ ├── entry.client.tsx │ │ │ ├── entry.server.tsx │ │ │ ├── models/ │ │ │ │ ├── note.server.ts │ │ │ │ └── user.server.ts │ │ │ ├── root.tsx │ │ │ ├── routes/ │ │ │ │ ├── healthcheck.tsx │ │ │ │ ├── index.tsx │ │ │ │ ├── join.tsx │ │ │ │ ├── login.tsx │ │ │ │ ├── logout.tsx │ │ │ │ ├── notes/ │ │ │ │ │ ├── $noteId.tsx │ │ │ │ │ ├── index.tsx │ │ │ │ │ └── new.tsx │ │ │ │ └── notes.tsx │ │ │ ├── session.server.ts │ │ │ ├── utils.test.ts │ │ │ └── utils.ts │ │ ├── custom-server.js │ │ ├── cypress/ │ │ │ ├── .eslintrc.js │ │ │ ├── e2e/ │ │ │ │ └── smoke.cy.ts │ │ │ ├── fixtures/ │ │ │ │ └── example.json │ │ │ ├── support/ │ │ │ │ ├── commands.ts │ │ │ │ ├── create-user.ts │ │ │ │ ├── delete-user.ts │ │ │ │ └── e2e.ts │ │ │ └── tsconfig.json │ │ ├── cypress.config.ts │ │ ├── fly.toml │ │ ├── mocks/ │ │ │ ├── README.md │ │ │ └── index.js │ │ ├── package.json │ │ ├── prisma/ │ │ │ ├── migrations/ │ │ │ │ ├── 20220713162558_init/ │ │ │ │ │ └── migration.sql │ │ │ │ └── migration_lock.toml │ │ │ ├── schema.prisma │ │ │ └── seed.ts │ │ ├── remix.config.js │ │ ├── remix.env.d.ts │ │ ├── remix.init/ │ │ │ ├── gitignore │ │ │ ├── index.js │ │ │ └── package.json │ │ ├── start.sh │ │ ├── tailwind.config.js │ │ ├── test/ │ │ │ └── setup-test-env.ts │ │ ├── tsconfig.json │ │ └── vitest.config.ts │ └── simple/ │ ├── .eslintrc.js │ ├── .gitignore │ ├── README.md │ ├── app/ │ │ ├── entry.client.tsx │ │ ├── entry.server.tsx │ │ ├── root.tsx │ │ └── routes/ │ │ └── index.tsx │ ├── package.json │ ├── remix.config.js │ ├── remix.env.d.ts │ └── tsconfig.json ├── package.json ├── src/ │ ├── constants.ts │ ├── entries/ │ │ ├── cli.ts │ │ └── lib.ts │ ├── plugins/ │ │ ├── hmr-fix.ts │ │ ├── inject.ts │ │ ├── remix.ts │ │ └── transform.ts │ ├── utils/ │ │ ├── code.ts │ │ ├── general.ts │ │ └── version.ts │ └── vite.ts ├── tools/ │ └── build.js └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintignore ================================================ /node_modules/** /declarations /examples/** /cli.js /lib.js /lib.esm.js ================================================ FILE: .gitattributes ================================================ # .gitattributes # Makes sure all line endings are LF. * text=auto eol=lf ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.yaml ================================================ name: Report a bug description: ——— labels: [bug] body: - type: markdown attributes: value: | # Thanks for reporting this bug! Help us replicate and find a fix for the issue by filling in this form. - type: textarea attributes: label: Description description: | Describe the issue and how to replicate it. If possible, please include a minimal example to reproduce the issue. validations: required: true - type: input attributes: label: Library version description: | Output of the `serve --version` command validations: required: true - type: input attributes: label: Node version description: Output of the `node --version` command validations: required: true ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.yaml ================================================ name: Suggest an improvement or new feature description: ——— labels: [enhancement] body: - type: markdown attributes: value: | # Thanks for filing this feature request! Help us understanding this feature and the need for it better by filling in this form. - type: textarea attributes: label: Description description: Describe the feature in detail validations: required: true - type: textarea attributes: label: Why description: Why should we add this feature? What are potential use cases for it? validations: required: true - type: textarea attributes: label: Alternatives description: Describe the alternatives you have considered, or existing workarounds validations: required: true ================================================ FILE: .github/PULL_REQUEST_TEMPLATE/default.md ================================================ ## Related Issues ## Description ### Added ### Changed ### Removed ## Caveats/Problems/Issues ## Checklist - [ ] The issues that this PR fixes/closes have been mentioned above. - [ ] What this PR adds/changes/removes has been explained. - [ ] All tests (`pnpm test`) pass. - [ ] The linter (`pnpm lint`) does not throw an errors. - [ ] All added/modified code has been commented, and methods/classes/constants/types have been annotated with TSDoc comments. ================================================ FILE: .github/workflows/publish.yml ================================================ name: Publish to NPM on: release: types: [created] jobs: build: runs-on: ubuntu-latest steps: - name: Cache id: node-modules uses: actions/cache@v3 with: path: node_modules key: ${{ runner.os }}-node-modules-${{ hashFiles('**/yarn.lock') }} restore-keys: | ${{ runner.os }}-node-modules- - name: Checkout uses: actions/checkout@v3 - name: Setup Node uses: actions/setup-node@v3 with: node-version: '18.x' registry-url: 'https://registry.npmjs.org' - name: Install dependencies and build 🔧 run: yarn && yarn build - name: Publish package on NPM 📦 run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} ================================================ FILE: .gitignore ================================================ # .gitignore # A list of files and folders that should not be tracked by Git. node_modules/ coverage/ build/ .cache/ .idea/ .vscode/ *.log *.tgz *.bak *.tmp cli.js lib.js lib.esm.js declarations ================================================ FILE: .npmrc ================================================ # .npmrc # Configuration for pnpm. # Uses the exact version instead of any within-patch-range version of an # installed package. save-exact=true # Do not error out on missing peer dependencies. strict-peer-dependencies=false ================================================ FILE: .prettierignore ================================================ node_modules/** declarations/** examples/** cli.js lib.js lib.esm.js ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2022 Mayke Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # remix-vite




`remix-vite` helps you serve [Remix](https://remix.run/) apps locally using [Vite](https://vitejs.dev/). ## Usage The quickest way to get started is to just run `npx remix-vite` in your project's directory. If you prefer, you can also install the package globally (you'll need at least [Node LTS](https://github.com/nodejs/Release#release-schedule)): ```bash > npm install --global remix-vite ``` Once that's done, you can run this command inside your project's directory... ```bash > remix-vite ``` Now you understand how the package works! :tada: ## Custom Remix Server If you want to use `remix-vite` with a custom remix server, you can do so by integrating your server with vite dev server. Let's say you have a custom Express server and you want to use it with `remix-vite`. Here is how you can do it: ```js const express = require('express'); const { createRequestHandler } = require('@remix-run/express'); const { createRemixViteDevServer, getRemixViteBuild } = require('remix-vite'); const app = express(); // Create a remix-vite dev server. createRemixViteDevServer().then((remixViteDevServer) => { // Use remix-vite dev server as middleware. app.use(remixViteDevServer.middlewares); app.all('*', async (req, res, next) => { purgeRequireCache(); // Get the remix build generated by remix-vite. const remixBuild = await getRemixViteBuild(remixViteDevServer); // Create a remix express request handler. const requestHandler = createRequestHandler({ build: remixBuild }); await requestHandler(req, res, next); }); // Start the server. app.listen(3000, () => { console.log('Listening at http://localhost:3000'); }); }); function purgeRequireCache() { // purge require cache on requests for "server side HMR" this won't let // you have in-memory objects between requests in development. for (const key in require.cache) { delete require.cache[key]; } } ``` ## Change default host and port If you want to change the host and port just pass --host and --port flag to remix-vite. Default host is `localhost` and port is `3000` `> remix-vite --port=4000` ## Issues If you want a feature to be added, or wish to report a bug, please open an issue [here](https://github.com/sudomf/remix-vite/issues/new). ## Author Mayke Freitas ([@sudomf](https://twitter.com/maykedev))
================================================ FILE: config/husky/pre-commit ================================================ #!/bin/sh # config/husky/pre-commit # Run `lint-staged` before every commit. . "$(dirname "$0")/_/husky.sh" FORCE_COLOR=2 yarn lint-staged ================================================ FILE: examples/complex/.dockerignore ================================================ /node_modules *.log .DS_Store .env /.cache /public/build /build ================================================ FILE: examples/complex/.eslintrc.js ================================================ /** @type {import('@types/eslint').Linter.BaseConfig} */ module.exports = { extends: [ "@remix-run/eslint-config", "@remix-run/eslint-config/node", "@remix-run/eslint-config/jest-testing-library", "prettier", ], env: { "cypress/globals": true, }, plugins: ["cypress"], // we're using vitest which has a very similar API to jest // (so the linting plugins work nicely), but it means we have to explicitly // set the jest version. settings: { jest: { version: 28, }, }, }; ================================================ FILE: examples/complex/.gitignore ================================================ # We don't want lockfiles in stacks, as people could use a different package manager # This part will be removed by `remix.init` package-lock.json yarn.lock pnpm-lock.yaml pnpm-lock.yml node_modules /build /public/build .env /cypress/screenshots /cypress/videos /prisma/data.db /prisma/data.db-journal /app/styles/tailwind.css ================================================ FILE: examples/complex/.gitpod.Dockerfile ================================================ FROM gitpod/workspace-full # Install Fly RUN curl -L https://fly.io/install.sh | sh ENV FLYCTL_INSTALL="/home/gitpod/.fly" ENV PATH="$FLYCTL_INSTALL/bin:$PATH" # Install GitHub CLI RUN brew install gh ================================================ FILE: examples/complex/.gitpod.yml ================================================ # https://www.gitpod.io/docs/config-gitpod-file image: file: .gitpod.Dockerfile ports: - port: 3000 onOpen: notify tasks: - name: Restore .env file command: | if [ -f .env ]; then # If this workspace already has a .env, don't override it # Local changes survive a workspace being opened and closed # but they will not persist between separate workspaces for the same repo echo "Found .env in workspace" else # There is no .env if [ ! -n "${ENV}" ]; then # There is no $ENV from a previous workspace # Default to the example .env echo "Setting example .env" cp .env.example .env else # After making changes to .env, run this line to persist it to $ENV # eval $(gp env -e ENV="$(base64 .env | tr -d '\n')") # # Environment variables set this way are shared between all your workspaces for this repo # The lines below will read $ENV and print a .env file echo "Restoring .env from Gitpod" echo "${ENV}" | base64 -d | tee .env > /dev/null fi fi - init: npm install command: npm run setup && npm run dev vscode: extensions: - ms-azuretools.vscode-docker - esbenp.prettier-vscode - dbaeumer.vscode-eslint - bradlc.vscode-tailwindcss ================================================ FILE: examples/complex/.npmrc ================================================ legacy-peer-deps=true ================================================ FILE: examples/complex/.prettierignore ================================================ node_modules /build /public/build .env /app/styles/tailwind.css ================================================ FILE: examples/complex/Dockerfile ================================================ # base node image FROM node:16-bullseye-slim as base # set for base and all layer that inherit from it ENV NODE_ENV production # Install openssl for Prisma RUN apt-get update && apt-get install -y openssl sqlite3 # Install all node_modules, including dev dependencies FROM base as deps WORKDIR /myapp ADD package.json .npmrc ./ RUN npm install --production=false # Setup production node_modules FROM base as production-deps WORKDIR /myapp COPY --from=deps /myapp/node_modules /myapp/node_modules ADD package.json .npmrc ./ RUN npm prune --production # Build the app FROM base as build WORKDIR /myapp COPY --from=deps /myapp/node_modules /myapp/node_modules ADD prisma . RUN npx prisma generate ADD . . RUN npm run build # Finally, build the production image with minimal footprint FROM base ENV DATABASE_URL=file:/data/sqlite.db ENV PORT="8080" ENV NODE_ENV="production" # add shortcut for connecting to database CLI RUN echo "#!/bin/sh\nset -x\nsqlite3 \$DATABASE_URL" > /usr/local/bin/database-cli && chmod +x /usr/local/bin/database-cli WORKDIR /myapp COPY --from=production-deps /myapp/node_modules /myapp/node_modules COPY --from=build /myapp/node_modules/.prisma /myapp/node_modules/.prisma COPY --from=build /myapp/build /myapp/build COPY --from=build /myapp/public /myapp/public COPY --from=build /myapp/package.json /myapp/package.json COPY --from=build /myapp/start.sh /myapp/start.sh COPY --from=build /myapp/prisma /myapp/prisma ENTRYPOINT [ "./start.sh" ] ================================================ FILE: examples/complex/README.md ================================================ # Remix Indie Stack ![The Remix Indie Stack](https://repository-images.githubusercontent.com/465928257/a241fa49-bd4d-485a-a2a5-5cb8e4ee0abf) Learn more about [Remix Stacks](https://remix.run/stacks). ``` npx create-remix@latest --template remix-run/indie-stack ``` ## What's in the stack - [Fly app deployment](https://fly.io) with [Docker](https://www.docker.com/) - Production-ready [SQLite Database](https://sqlite.org) - Healthcheck endpoint for [Fly backups region fallbacks](https://fly.io/docs/reference/configuration/#services-http_checks) - [GitHub Actions](https://github.com/features/actions) for deploy on merge to production and staging environments - Email/Password Authentication with [cookie-based sessions](https://remix.run/docs/en/v1/api/remix#createcookiesessionstorage) - Database ORM with [Prisma](https://prisma.io) - Styling with [Tailwind](https://tailwindcss.com/) - End-to-end testing with [Cypress](https://cypress.io) - Local third party request mocking with [MSW](https://mswjs.io) - Unit testing with [Vitest](https://vitest.dev) and [Testing Library](https://testing-library.com) - Code formatting with [Prettier](https://prettier.io) - Linting with [ESLint](https://eslint.org) - Static Types with [TypeScript](https://typescriptlang.org) Not a fan of bits of the stack? Fork it, change it, and use `npx create-remix --template your/repo`! Make it your own. ## Quickstart Click this button to create a [Gitpod](https://gitpod.io) workspace with the project set up and Fly pre-installed [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/from-referrer/) ## Development - This step only applies if you've opted out of having the CLI install dependencies for you: ```sh npx remix init ``` - Initial setup: _If you just generated this project, this step has been done for you._ ```sh npm run setup ``` - Start dev server: ```sh npm run dev ``` This starts your app in development mode, rebuilding assets on file changes. The database seed script creates a new user with some data you can use to get started: - Email: `rachel@remix.run` - Password: `racheliscool` ### Relevant code: This is a pretty simple note-taking app, but it's a good example of how you can build a full stack app with Prisma and Remix. The main functionality is creating users, logging in and out, and creating and deleting notes. - creating users, and logging in and out [./app/models/user.server.ts](./app/models/user.server.ts) - user sessions, and verifying them [./app/session.server.ts](./app/session.server.ts) - creating, and deleting notes [./app/models/note.server.ts](./app/models/note.server.ts) ## Deployment This Remix Stack comes with two GitHub Actions that handle automatically deploying your app to production and staging environments. Prior to your first deployment, you'll need to do a few things: - [Install Fly](https://fly.io/docs/getting-started/installing-flyctl/) - Sign up and log in to Fly ```sh fly auth signup ``` > **Note:** If you have more than one Fly account, ensure that you are signed into the same account in the Fly CLI as you are in the browser. In your terminal, run `fly auth whoami` and ensure the email matches the Fly account signed into the browser. - Create two apps on Fly, one for staging and one for production: ```sh fly apps create indie-stack-template fly apps create indie-stack-template-staging ``` > **Note:** Make sure this name matches the `app` set in your `fly.toml` file. Otherwise, you will not be able to deploy. - Initialize Git. ```sh git init ``` - Create a new [GitHub Repository](https://repo.new), and then add it as the remote for your project. **Do not push your app yet!** ```sh git remote add origin ``` - Add a `FLY_API_TOKEN` to your GitHub repo. To do this, go to your user settings on Fly and create a new [token](https://web.fly.io/user/personal_access_tokens/new), then add it to [your repo secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) with the name `FLY_API_TOKEN`. - Add a `SESSION_SECRET` to your fly app secrets, to do this you can run the following commands: ```sh fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app indie-stack-template fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app indie-stack-template-staging ``` If you don't have openssl installed, you can also use [1password](https://1password.com/password-generator/) to generate a random secret, just replace `$(openssl rand -hex 32)` with the generated secret. - Create a persistent volume for the sqlite database for both your staging and production environments. Run the following: ```sh fly volumes create data --size 1 --app indie-stack-template fly volumes create data --size 1 --app indie-stack-template-staging ``` Now that everything is set up you can commit and push your changes to your repo. Every commit to your `main` branch will trigger a deployment to your production environment, and every commit to your `dev` branch will trigger a deployment to your staging environment. ### Connecting to your database The sqlite database lives at `/data/sqlite.db` in your deployed application. You can connect to the live database by running `fly ssh console -C database-cli`. ### Getting Help with Deployment If you run into any issues deploying to Fly, make sure you've followed all of the steps above and if you have, then post as many details about your deployment (including your app name) to [the Fly support community](https://community.fly.io). They're normally pretty responsive over there and hopefully can help resolve any of your deployment issues and questions. ## GitHub Actions We use GitHub Actions for continuous integration and deployment. Anything that gets into the `main` branch will be deployed to production after running tests/build/etc. Anything in the `dev` branch will be deployed to staging. ## Testing ### Cypress We use Cypress for our End-to-End tests in this project. You'll find those in the `cypress` directory. As you make changes, add to an existing file or create a new file in the `cypress/e2e` directory to test your changes. We use [`@testing-library/cypress`](https://testing-library.com/cypress) for selecting elements on the page semantically. To run these tests in development, run `npm run test:e2e:dev` which will start the dev server for the app as well as the Cypress client. Make sure the database is running in docker as described above. We have a utility for testing authenticated features without having to go through the login flow: ```ts cy.login(); // you are now logged in as a new user ``` We also have a utility to auto-delete the user at the end of your test. Just make sure to add this in each test file: ```ts afterEach(() => { cy.cleanupUser(); }); ``` That way, we can keep your local db clean and keep your tests isolated from one another. ### Vitest For lower level tests of utilities and individual components, we use `vitest`. We have DOM-specific assertion helpers via [`@testing-library/jest-dom`](https://testing-library.com/jest-dom). ### Type Checking This project uses TypeScript. It's recommended to get TypeScript set up for your editor to get a really great in-editor experience with type checking and auto-complete. To run type checking across the whole project, run `npm run typecheck`. ### Linting This project uses ESLint for linting. That is configured in `.eslintrc.js`. ### Formatting We use [Prettier](https://prettier.io/) for auto-formatting in this project. It's recommended to install an editor plugin (like the [VSCode Prettier plugin](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)) to get auto-formatting on save. There's also a `npm run format` script you can run to format all files in the project. ================================================ FILE: examples/complex/app/db.server.ts ================================================ import { PrismaClient } from "@prisma/client"; let prisma: PrismaClient; declare global { var __db__: PrismaClient; } // this is needed because in development we don't want to restart // the server with every change, but we want to make sure we don't // create a new connection to the DB with every change either. // in production we'll have a single connection to the DB. if (process.env.NODE_ENV === "production") { prisma = new PrismaClient(); } else { if (!global.__db__) { global.__db__ = new PrismaClient(); } prisma = global.__db__; prisma.$connect(); } export { prisma }; ================================================ FILE: examples/complex/app/entry.client.tsx ================================================ import { RemixBrowser } from "@remix-run/react"; import { startTransition, StrictMode } from "react"; import { hydrateRoot } from "react-dom/client"; const hydrate = () => { startTransition(() => { hydrateRoot( document, ); }); }; if (window.requestIdleCallback) { window.requestIdleCallback(hydrate); } else { // Safari doesn't support requestIdleCallback // https://caniuse.com/requestidlecallback window.setTimeout(hydrate, 1); } ================================================ FILE: examples/complex/app/entry.server.tsx ================================================ import { PassThrough } from "stream"; import type { EntryContext } from "@remix-run/node"; import { Response } from "@remix-run/node"; import { RemixServer } from "@remix-run/react"; import isbot from "isbot"; import { renderToPipeableStream } from "react-dom/server"; const ABORT_DELAY = 5000; export default function handleRequest( request: Request, responseStatusCode: number, responseHeaders: Headers, remixContext: EntryContext ) { const callbackName = isbot(request.headers.get("user-agent")) ? "onAllReady" : "onShellReady"; return new Promise(async (resolve, reject) => { let didError = false; const { pipe, abort } = renderToPipeableStream( , { [callbackName]: () => { const body = new PassThrough(); responseHeaders.set("Content-Type", "text/html"); resolve( new Response(body, { headers: responseHeaders, status: didError ? 500 : responseStatusCode, }) ); pipe(body); }, onShellError: (err: unknown) => { reject(err); }, onError: (error: unknown) => { didError = true; console.error(error); }, } ); setTimeout(abort, ABORT_DELAY); }); } ================================================ FILE: examples/complex/app/models/note.server.ts ================================================ import type { User, Note } from "@prisma/client"; import { prisma } from "~/db.server"; export type { Note } from "@prisma/client"; export function getNote({ id, userId, }: Pick & { userId: User["id"]; }) { return prisma.note.findFirst({ select: { id: true, body: true, title: true }, where: { id, userId }, }); } export function getNoteListItems({ userId }: { userId: User["id"] }) { return prisma.note.findMany({ where: { userId }, select: { id: true, title: true }, orderBy: { updatedAt: "desc" }, }); } export function createNote({ body, title, userId, }: Pick & { userId: User["id"]; }) { return prisma.note.create({ data: { title, body, user: { connect: { id: userId, }, }, }, }); } export function deleteNote({ id, userId, }: Pick & { userId: User["id"] }) { return prisma.note.deleteMany({ where: { id, userId }, }); } ================================================ FILE: examples/complex/app/models/user.server.ts ================================================ import type { Password, User } from "@prisma/client"; import bcrypt from "bcryptjs"; import { prisma } from "~/db.server"; export type { User } from "@prisma/client"; export async function getUserById(id: User["id"]) { return prisma.user.findUnique({ where: { id } }); } export async function getUserByEmail(email: User["email"]) { return prisma.user.findUnique({ where: { email } }); } export async function createUser(email: User["email"], password: string) { const hashedPassword = await bcrypt.hash(password, 10); return prisma.user.create({ data: { email, password: { create: { hash: hashedPassword, }, }, }, }); } export async function deleteUserByEmail(email: User["email"]) { return prisma.user.delete({ where: { email } }); } export async function verifyLogin( email: User["email"], password: Password["hash"] ) { const userWithPassword = await prisma.user.findUnique({ where: { email }, include: { password: true, }, }); if (!userWithPassword || !userWithPassword.password) { return null; } const isValid = await bcrypt.compare( password, userWithPassword.password.hash ); if (!isValid) { return null; } const { password: _password, ...userWithoutPassword } = userWithPassword; return userWithoutPassword; } ================================================ FILE: examples/complex/app/root.tsx ================================================ import type { LinksFunction, LoaderArgs } from "@remix-run/node"; import { json } from "@remix-run/node"; import { Links, LiveReload, Meta, Outlet, Scripts, ScrollRestoration, } from "@remix-run/react"; import tailwindStylesheetUrl from "./styles/tailwind.css"; import { getUser } from "./session.server"; export const links: LinksFunction = () => { return [{ rel: "stylesheet", href: tailwindStylesheetUrl }]; }; export async function loader({ request }: LoaderArgs) { return json({ user: await getUser(request), }); } export default function App() { return ( ); } ================================================ FILE: examples/complex/app/routes/healthcheck.tsx ================================================ // learn more: https://fly.io/docs/reference/configuration/#services-http_checks import type { LoaderArgs } from "@remix-run/node"; import { prisma } from "~/db.server"; export async function loader({ request }: LoaderArgs) { const host = request.headers.get("X-Forwarded-Host") ?? request.headers.get("host"); try { const url = new URL("/", `http://${host}`); // if we can connect to the database and make a simple query // and make a HEAD request to ourselves, then we're good. await Promise.all([ prisma.user.count(), fetch(url.toString(), { method: "HEAD" }).then((r) => { if (!r.ok) return Promise.reject(r); }), ]); return new Response("OK"); } catch (error: unknown) { console.log("healthcheck ❌", { error }); return new Response("ERROR", { status: 500 }); } } ================================================ FILE: examples/complex/app/routes/index.tsx ================================================ import { Link } from "@remix-run/react"; import { useOptionalUser } from "~/utils"; export default function Index() { const user = useOptionalUser(); return (
{[ { src: "https://user-images.githubusercontent.com/1500684/157764397-ccd8ea10-b8aa-4772-a99b-35de937319e1.svg", alt: "Fly.io", href: "https://fly.io", }, { src: "https://user-images.githubusercontent.com/1500684/157764395-137ec949-382c-43bd-a3c0-0cb8cb22e22d.svg", alt: "SQLite", href: "https://sqlite.org", }, { src: "https://user-images.githubusercontent.com/1500684/157764484-ad64a21a-d7fb-47e3-8669-ec046da20c1f.svg", alt: "Prisma", href: "https://prisma.io", }, { src: "https://user-images.githubusercontent.com/1500684/157764276-a516a239-e377-4a20-b44a-0ac7b65c8c14.svg", alt: "Tailwind", href: "https://tailwindcss.com", }, { src: "https://user-images.githubusercontent.com/1500684/157764454-48ac8c71-a2a9-4b5e-b19c-edef8b8953d6.svg", alt: "Cypress", href: "https://www.cypress.io", }, { src: "https://user-images.githubusercontent.com/1500684/157772386-75444196-0604-4340-af28-53b236faa182.svg", alt: "MSW", href: "https://mswjs.io", }, { src: "https://user-images.githubusercontent.com/1500684/157772447-00fccdce-9d12-46a3-8bb4-fac612cdc949.svg", alt: "Vitest", href: "https://vitest.dev", }, { src: "https://user-images.githubusercontent.com/1500684/157772662-92b0dd3a-453f-4d18-b8be-9fa6efde52cf.png", alt: "Testing Library", href: "https://testing-library.com", }, { src: "https://user-images.githubusercontent.com/1500684/157772934-ce0a943d-e9d0-40f8-97f3-f464c0811643.svg", alt: "Prettier", href: "https://prettier.io", }, { src: "https://user-images.githubusercontent.com/1500684/157772990-3968ff7c-b551-4c55-a25c-046a32709a8e.svg", alt: "ESLint", href: "https://eslint.org", }, { src: "https://user-images.githubusercontent.com/1500684/157773063-20a0ed64-b9f8-4e0b-9d1e-0b65a3d4a6db.svg", alt: "TypeScript", href: "https://typescriptlang.org", }, ].map((img) => ( {img.alt} ))}
); } ================================================ FILE: examples/complex/app/routes/join.tsx ================================================ import type { ActionArgs, LoaderArgs, MetaFunction } from "@remix-run/node"; import { json, redirect } from "@remix-run/node"; import { Form, Link, useActionData, useSearchParams } from "@remix-run/react"; import * as React from "react"; import { getUserId, createUserSession } from "~/session.server"; import { createUser, getUserByEmail } from "~/models/user.server"; import { safeRedirect, validateEmail } from "~/utils"; export async function loader({ request }: LoaderArgs) { const userId = await getUserId(request); if (userId) return redirect("/"); return json({}); } export async function action({ request }: ActionArgs) { const formData = await request.formData(); const email = formData.get("email"); const password = formData.get("password"); const redirectTo = safeRedirect(formData.get("redirectTo"), "/"); if (!validateEmail(email)) { return json( { errors: { email: "Email is invalid", password: null } }, { status: 400 } ); } if (typeof password !== "string" || password.length === 0) { return json( { errors: { email: null, password: "Password is required" } }, { status: 400 } ); } if (password.length < 8) { return json( { errors: { email: null, password: "Password is too short" } }, { status: 400 } ); } const existingUser = await getUserByEmail(email); if (existingUser) { return json( { errors: { email: "A user already exists with this email", password: null, }, }, { status: 400 } ); } const user = await createUser(email, password); return createUserSession({ request, userId: user.id, remember: false, redirectTo, }); } export const meta: MetaFunction = () => { return { title: "Sign Up", }; }; export default function Join() { const [searchParams] = useSearchParams(); const redirectTo = searchParams.get("redirectTo") ?? undefined; const actionData = useActionData(); const emailRef = React.useRef(null); const passwordRef = React.useRef(null); React.useEffect(() => { if (actionData?.errors?.email) { emailRef.current?.focus(); } else if (actionData?.errors?.password) { passwordRef.current?.focus(); } }, [actionData]); return (
{actionData?.errors?.email && (
{actionData.errors.email}
)}
{actionData?.errors?.password && (
{actionData.errors.password}
)}
Already have an account?{" "} Log in
); } ================================================ FILE: examples/complex/app/routes/login.tsx ================================================ import type { ActionArgs, LoaderArgs, MetaFunction } from "@remix-run/node"; import { json, redirect } from "@remix-run/node"; import { Form, Link, useActionData, useSearchParams } from "@remix-run/react"; import * as React from "react"; import { createUserSession, getUserId } from "~/session.server"; import { verifyLogin } from "~/models/user.server"; import { safeRedirect, validateEmail } from "~/utils"; export async function loader({ request }: LoaderArgs) { const userId = await getUserId(request); if (userId) return redirect("/"); return json({}); } export async function action({ request }: ActionArgs) { const formData = await request.formData(); const email = formData.get("email"); const password = formData.get("password"); const redirectTo = safeRedirect(formData.get("redirectTo"), "/notes"); const remember = formData.get("remember"); if (!validateEmail(email)) { return json( { errors: { email: "Email is invalid", password: null } }, { status: 400 } ); } if (typeof password !== "string" || password.length === 0) { return json( { errors: { email: null, password: "Password is required" } }, { status: 400 } ); } if (password.length < 8) { return json( { errors: { email: null, password: "Password is too short" } }, { status: 400 } ); } const user = await verifyLogin(email, password); if (!user) { return json( { errors: { email: "Invalid email or password", password: null } }, { status: 400 } ); } return createUserSession({ request, userId: user.id, remember: remember === "on" ? true : false, redirectTo, }); } export const meta: MetaFunction = () => { return { title: "Login", }; }; export default function LoginPage() { const [searchParams] = useSearchParams(); const redirectTo = searchParams.get("redirectTo") || "/notes"; const actionData = useActionData(); const emailRef = React.useRef(null); const passwordRef = React.useRef(null); React.useEffect(() => { if (actionData?.errors?.email) { emailRef.current?.focus(); } else if (actionData?.errors?.password) { passwordRef.current?.focus(); } }, [actionData]); return (
{actionData?.errors?.email && (
{actionData.errors.email}
)}
{actionData?.errors?.password && (
{actionData.errors.password}
)}
Don't have an account?{" "} Sign up
); } ================================================ FILE: examples/complex/app/routes/logout.tsx ================================================ import type { ActionArgs } from "@remix-run/node"; import { redirect } from "@remix-run/node"; import { logout } from "~/session.server"; export async function action({ request }: ActionArgs) { return logout(request); } export async function loader() { return redirect("/"); } ================================================ FILE: examples/complex/app/routes/notes/$noteId.tsx ================================================ import type { ActionArgs, LoaderArgs } from "@remix-run/node"; import { json, redirect } from "@remix-run/node"; import { Form, useCatch, useLoaderData } from "@remix-run/react"; import invariant from "tiny-invariant"; import { deleteNote, getNote } from "~/models/note.server"; import { requireUserId } from "~/session.server"; export async function loader({ request, params }: LoaderArgs) { const userId = await requireUserId(request); invariant(params.noteId, "noteId not found"); const note = await getNote({ userId, id: params.noteId }); if (!note) { throw new Response("Not Found", { status: 404 }); } return json({ note }); } export async function action({ request, params }: ActionArgs) { const userId = await requireUserId(request); invariant(params.noteId, "noteId not found"); await deleteNote({ userId, id: params.noteId }); return redirect("/notes"); } export default function NoteDetailsPage() { const data = useLoaderData(); return (

{data.note.title}

{data.note.body}


); } export function ErrorBoundary({ error }: { error: Error }) { console.error(error); return
An unexpected error occurred: {error.message}
; } export function CatchBoundary() { const caught = useCatch(); if (caught.status === 404) { return
Note not found
; } throw new Error(`Unexpected caught response with status: ${caught.status}`); } ================================================ FILE: examples/complex/app/routes/notes/index.tsx ================================================ import { Link } from "@remix-run/react"; export default function NoteIndexPage() { return (

No note selected. Select a note on the left, or{" "} create a new note.

); } ================================================ FILE: examples/complex/app/routes/notes/new.tsx ================================================ import type { ActionArgs } from "@remix-run/node"; import { json, redirect } from "@remix-run/node"; import { Form, useActionData } from "@remix-run/react"; import * as React from "react"; import { createNote } from "~/models/note.server"; import { requireUserId } from "~/session.server"; export async function action({ request }: ActionArgs) { const userId = await requireUserId(request); const formData = await request.formData(); const title = formData.get("title"); const body = formData.get("body"); if (typeof title !== "string" || title.length === 0) { return json( { errors: { title: "Title is required", body: null } }, { status: 400 } ); } if (typeof body !== "string" || body.length === 0) { return json( { errors: { title: null, body: "Body is required" } }, { status: 400 } ); } const note = await createNote({ title, body, userId }); return redirect(`/notes/${note.id}`); } export default function NewNotePage() { const actionData = useActionData(); const titleRef = React.useRef(null); const bodyRef = React.useRef(null); React.useEffect(() => { if (actionData?.errors?.title) { titleRef.current?.focus(); } else if (actionData?.errors?.body) { bodyRef.current?.focus(); } }, [actionData]); return (
{actionData?.errors?.title && (
{actionData.errors.title}
)}