Giter Site home page Giter Site logo

remix-run / examples Goto Github PK

View Code? Open in Web Editor NEW
868.0 11.0 203.0 10.97 MB

A community-driven repository showcasing examples using Remix ๐Ÿ’ฟ

License: MIT License

JavaScript 6.72% TypeScript 78.63% CSS 14.04% Shell 0.13% Dockerfile 0.45% Rust 0.01% SCSS 0.02%

examples's Introduction

Remix Examples

Welcome to @remix-run/examples, the community-driven repository.

Here you'll find various examples of using Remix to accomplish certain tasks.

Each example is a complete application including a build and even a button to preview a live instance of the app so you can play with it.

Remember to check out the README for each example before getting started.

You can also initialize a new project with any of these examples using the --template flag of the create-remix CLI.

For example:

npx create-remix@latest --template remix-run/examples/<example-dir>

Enjoy!

Contributing

Please see our contribution guide.

examples's People

Contributors

chaance avatar dependabot[bot] avatar efkann avatar github-actions[bot] avatar ikorecky avatar imertz avatar irvile avatar jacob-ebey avatar johnpolacek avatar leapful avatar levischouten avatar machour avatar marcisbee avatar markdalgleish avatar maxrchung avatar mcansh avatar michaeldeboey avatar nexxeln avatar nightgrey avatar noahsb avatar penx avatar ralinc avatar richardscarrott avatar robinclowers avatar ryanflorence avatar sergiodxa avatar somidivian avatar strudso avatar takagimeow avatar themosaad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

examples's Issues

tailwind styles are not processed in v1.19.2 but are in v1.19.1

What version of Remix are you using?

1.19.2

Are all your remix dependencies & dev-dependencies using the same version?

  • Yes

Steps to Reproduce

npx create-remix@latest remix-app --template examples/tailwindcss install the deps and run now styles are present

if you change the deps to use v1.19.1 styles are back

Expected Behavior

it should parse tailwind styles and add them to the style sheet

Actual Behavior

its not parsing any tailwind styles

auth0 example is broken

Trying to run the remix-auth-auth0 locally or in Codesandbox results in the following error when you click the login button:

TypeError: Cannot read property 'startsWith' of undefined
    at Auth0Strategy.getCallbackURL (/sandbox/node_modules/remix-auth-oauth2/build/index.js:182:30)
    at Auth0Strategy.authenticate (/sandbox/node_modules/remix-auth-oauth2/build/index.js:78:32)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at Object.callRouteActionRR (/sandbox/node_modules/@remix-run/server-runtime/dist/data.js:24:16)
    at callLoaderOrAction (/sandbox/node_modules/@remix-run/router/router.ts:3125:14)
    at submit (/sandbox/node_modules/@remix-run/router/router.ts:2609:16)
    at queryImpl (/sandbox/node_modules/@remix-run/router/router.ts:2544:22)
    at Object.queryRoute (/sandbox/node_modules/@remix-run/router/router.ts:2494:18)
    at handleDataRequestRR (/sandbox/node_modules/@remix-run/server-runtime/dist/server.js:81:20)
    at requestHandler (/sandbox/node_modules/@remix-run/server-runtime/dist/server.js:55:18)

Chakra Error/Catch Boundaries lose ChakraContext - but only sometimes

I have the example chakra repo as a base template, I have not modified the provided Error/Catch Boundaries in the root.tsx, and I have none elsewhere.

I have noticed that sometimes when one of these boundaries are hit, there is no theme at all, sometimes there is.

For example: If I navigate directly to a page that doesn't exist I get (with theme):
image

If I click a link inside my app that takes me to a page that doesn't exist (same url):
image

The Chakra Theme is missing.

There are also other instances eg when throwing / erroring from a loader - sometimes the theme is there, sometimes it isn't there, though I haven't been able to narrow down when so can't provide replication for that.

In all instances though, pressing "Back" on my browser will take me back BUT there is NO theme / styling whatsoever on the previous page, it's just plain text/images, it's like all the css has completely disappeared.

I also tried following the example provided by Chakra (which uses renderToString instead of renderToPipeableStream, but then error boundaries are even worse and looking at their issues, you have to create a bunch of dunder routes and it's a real trickery to get anything working (and then of course you lose the streaming ability).

Upgrade S3 example to use the newest SDK.

Recently, the AWS SDK v3 has been released and its now the recommended way to interact with AWS.

I tried to upgrade the S3 example myself, like this:

// ... in s3.server.ts
const {
  AWS_ACCESS_KEY_ID,
  AWS_SECRET_ACCESS_KEY,
  S3_STORAGE_BUCKET,
  S3_STORAGE_REGION,
} = process.env;

invariant(AWS_ACCESS_KEY_ID, 'AWS_ACCESS_KEY_ID is required');
invariant(AWS_SECRET_ACCESS_KEY, 'AWS_SECRET_ACCESS_KEY is required');
invariant(S3_STORAGE_BUCKET, 'S3_STORAGE_BUCKET is required');
invariant(S3_STORAGE_REGION, 'S3_STORAGE_REGION is required');

// ... rest stays same

export const uploadStream = ({
  Key,
}: Pick<PutObjectCommandInput, 'Key'>) => {
  const s3Client = new S3Client({ region: S3_STORAGE_REGION });
  const pass = new PassThrough();
  return {
    writeStream: pass,
    promise: s3Client.send(
      new PutObjectCommand({
        Body: pass,
        Bucket: S3_STORAGE_BUCKET,
        Key,
      }),
    ),
  };
};

// ... rest stays same

But it doesn't work because an error is thrown:

error NotImplemented: A header you provided implies functionality that is not implemented
    at throwDefaultError (/Users/dev/remix-app/node_modules/@aws-sdk/smithy-client/dist-cjs/default-error-handler.js:8:22)
    at deserializeAws_restXmlPutObjectCommandError (/Users/dev/remix-app/node_modules/@aws-sdk/client-s3/dist-cjs/protocols/Aws_restXml.js:5782:43)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at /Users/dev/remix-app/node_modules/@aws-sdk/middleware-serde/dist-cjs/deserializerMiddleware.js:7:24
    at /Users/dev/remix-app/node_modules/@aws-sdk/middleware-signing/dist-cjs/middleware.js:14:20
    at /Users/dev/remix-app/node_modules/@aws-sdk/middleware-retry/dist-cjs/retryMiddleware.js:27:46
    at /Users/dev/remix-app/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/flexibleChecksumsMiddleware.js:58:20
    at /Users/dev/remix-app/node_modules/@aws-sdk/middleware-logger/dist-cjs/loggerMiddleware.js:5:22
    at uploadStreamToS3 (/Users/dev/remix-app/app/features/recording/s3-upload-handler.server.ts:106:11) {
  '$fault': 'client',
  '$metadata': {
    httpStatusCode: 501,
    requestId: 'NSK9FW5CE2TW3NAN',
    extendedRequestId: '0zWgQIB0xmMtUuIYThFgN1MdD8hXAj/VcjHUaabT3RiB7jmh6hlTNfsDbxq9M6EMwp5rgAlVfcY=',
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  Code: 'NotImplemented',
  Header: 'Transfer-Encoding',
  RequestId: 'NSK9FW5CE2TW3NAN',
  HostId: '0zWgQIB0xmMtUuIYThFgN1MdD8hXAj/VcjHUaabT3RiB7jmh6hlTNfsDbxq9M6EMwp5rgAlVfcY='
}

by this line:

const file = await stream.promise;

in uploadStreamToS3().

I'm not skilled in S3, so I have no idea how to fix this.

Cookie but missing user in db, ends up being a promise and not redirecting to login

I got to this step:
https://remix.run/docs/en/1.18.1/tutorials/jokes#expected-errors

  1. I was logged in
  2. And then I "deleted" my db, and didn't seed,
  3. So my cookie was still present
    Ended up with an app error, but expected to be redirected to "login" page instead.
image

work around was this:
in session.server.ts

  export async function getUser(request: Request) {
    const userId = await getUserId(request);
    if (typeof userId !== "string") {
      return null;
    }
    
    const user = await db.user.findUnique({
      select: { id: true, username: true },
      where: { id: userId },
    });
    if (!user) {
      return logout(request);
    }
  
    return user;

and this in jokes.tsx

  export const loader = async ({ request }: LoaderArgs) => {
    const jokeListItems = await db.joke.findMany({
      orderBy: { createdAt: "desc" },
      select: { id: true, name: true },
      take: 5,
    });
    const user = await getUser(request);
    if(user instanceof Response){
        throw user;
    }
    return json({ jokeListItems, user });
  };

Very new to Remix, but this caught me a bit suprised, that it wouldn't result in redirect, because it was wrapped with async / await

Redirect param in /new route

Inside the /new.tsx file, I have find this line of code : return redirect(/threads/${thread.id}?redirectTo=/threads/new);
What is ?redirectTo inside that redirection? The Joke tutorial on the remix site don't have this url param.

chakra-ui example has hydration issues

The chakra-ui documentation shows that one must use hydrate and renderToString instead of hydrateRoot and renderToPipeableStream because of emotion css.

https://chakra-ui.com/getting-started/remix-guide

At the bottom of their documentation page, it suggests the official remix example with a link to this repo and an embedded codesandbox.

However, it doesn't seem to work properly using the method here, you can see the background color disappears after client hydration.

2023-09-01 09 59 10

I changed it to use the chakra recommendations in the code sandbox and it works with those. Would a PR to match be desired here?

https://codesandbox.io/p/sandbox/objective-stitch-ymvhrv

Vite + Styled Components Example

More of a request but is there any chance we can get an ideal example for using Styled Components with Vite? I tried my hand at it but would love to see something here to go off of.

Run `tsc` on changed examples

As reported by @mcansh in #83 (comment), we had some TypeScript errors when fixing the useActionData/useLoaderData usage.

It would be great if we could run tsc in CI, so we don't have to manually check for these kind of errors.

As I pointed out in #83 (comment), this would require running npm install & sometimes even more (like npx prisma migrate dev), otherwise TypeScript would complain. ๐Ÿ˜ข
This could be solved by having a setup script, but that still would require us to run npm install && npm run -s setup on all example folders (see #83 (comment)).

@mcansh Pointed out this could be prevented by only running the changed example and not the others (see #83 (comment)), which would probably require some git magic, but isn't unnecessary complicated I think.

with twind example has some error

Error: Cannot find module '/sandbox/build/index.js'
Require stack:

  • /sandbox/node_modules/@remix-run/serve/dist/index.js
  • /sandbox/node_modules/@remix-run/dev/dist/cli/commands.js
  • /sandbox/node_modules/@remix-run/dev/dist/cli/run.js
  • /sandbox/node_modules/@remix-run/dev/dist/cli/index.js
  • /sandbox/node_modules/@remix-run/dev/dist/index.js
  • /sandbox/node_modules/@remix-run/dev/dist/cli.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
    at Function.Module._load (internal/modules/cjs/loader.js:746:27)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:101:18)
    at /sandbox/node_modules/@remix-run/serve/dist/index.js:43:17
    at Layer.handle [as handle_request] (/sandbox/node_modules/express/lib/router/layer.js:95:5)
    at next (/sandbox/node_modules/express/lib/router/route.js:144:13)
    at next (/sandbox/node_modules/express/lib/router/route.js:140:7)
    at next (/sandbox/node_modules/express/lib/router/route.js:140:7)
    at next (/sandbox/node_modules/express/lib/router/route.js:140:7)

Blog tutorial needs update of routing

The official Blog Tutorial creates routes in a posts folder.

This needs to be changed:
app/routes/posts/index.tsx -> app/routes/posts._index.tsx
app/routes/posts/$slug.tsx -> app/routes/posts.$slug.tsx

Later in the tutorial, maybe there is a need for another change.

Instead of making a route to app/routes/posts/admin/$slug.tsx and changing this to app/routes/posts.admin.$slug.tsx, you could change app/routes/posts.$slug.tsx to app/routes/posts.(admin).$slug.tsx.
This worked for me, but needs extra consideration if one wants a back button on the post view.

I found these solutions on the page Route File Naming (v2)

How to implement CSS-in-JS with updated server code?

The current docs/example does not match up to the current default entry.server.{js|tsx} file so we're not sure how to implement in the latest code. Seems like a lot of juice-goodness in the new code we don't want to loose by just replacing that file with the example code.

Going to try my hand at figuring it out, but would love if someone who knows how to get it to work with the full default code could provide an update here. I'm happy to put a PR in, but just need to know how to get it to work.

Current example entry.server

https://github.com/remix-run/examples/blob/main/styled-components/app/entry.server.tsx#L1-L29

Current default entry.server

https://github.com/remix-run/remix/blob/main/templates/remix/app/entry.server.tsx#L1-L111

_official-realtime-app can't be run

Hi, when I run the example I get the error

node: bad option: --watch
ERROR: "dev:server" exited with 9.

my node version is 18.9.1

way to reproduce the error

npm install
npm run dev

Client Only Components Example has a Dependency Issue

When running npm i for the client-only components example, I get the following output:

(base) nick@nick-Laptop:~/Documents/GitHub/examples/client-only-components$ npm i
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: undefined@undefined
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^18.2.0" from the root project
npm ERR!   peer react@">=16.8" from @remix-run/[email protected]
npm ERR!   node_modules/@remix-run/react
npm ERR!     @remix-run/react@"*" from the root project
npm ERR!     peer @remix-run/react@"^1.1.1" from [email protected]
npm ERR!     node_modules/remix-utils
npm ERR!       remix-utils@"^2.7.0" from the root project
npm ERR!   1 more (react-dom)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^17.0.2" from [email protected]
npm ERR! node_modules/remix-utils
npm ERR!   remix-utils@"^2.7.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /home/nick/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/nick/.npm/_logs/2023-02-07T17_04_21_010Z-debug-0.log

Can someone help me update this?

MSW example not working

I am actually using the "indie stack" of remix, and I'm struggling to find a working setting for msw to work on both server and client side, I thought I would look into the example to find my solution but could not make this example works

here is the step I took :

npx create-remix@latest --template examples/msw
? TypeScript or JavaScript? (Use arrow keys)
โฏ TypeScript 
  JavaScript
? Do you want me to run `npm install`? (Y/n) y

Then running the dev server

$ npm run dev

> dev
> remix dev

Watching Remix app in development mode...
๐Ÿ’ฟ Built in 327ms
Remix App Server started at http://localhost:3000 (http://xxx.xxx.xx.x:3000)

When accessing the browser, here is what popup in my terminal :

There was an error running the data loader for route root
FetchError: request to https://my-mock-api.com/ failed, reason: getaddrinfo ENOTFOUND my-mock-api.com
    at ClientRequest.<anonymous> (/xxxxxx/remix-example/node_modules/@remix-run/web-fetch/src/fetch.js:111:11)
    at ClientRequest.emit (node:events:513:28)
    at TLSSocket.socketErrorListener (node:_http_client:494:9)
    at TLSSocket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)
GET / 500 - - 112.438 ms
GET /mockServiceWorker.js 404 - - 3.404 ms

GET /mockServiceWorker.js 404 - - 3.404 ms disappear if I run the msw init command line: npx msw init public/ --save

in the "indie stack", it looks like the initialization of msw is done differently with something like that in package.json :

{
...
"dev:remix": "cross-env NODE_ENV=development binode --require ./mocks -- @remix-run/dev:remix dev",
...
}

Create an example of an app with nested routes

I'm trying to organize my routes using route folders, but I can't seem to get it to work. I came to the examples repo to find a good example, but none of the examples show how to use route folders. Could someone who knows how Remix route folders works create an example? Thanks so much.

More severe hydration problems with styled-components

Hey there ๐Ÿ‘‹ I recently encountered a pretty severe issue with remix + styled components.

ref styled-components/styled-components#3924

1. Hydration errors in Production

In some cases the hydration errors described commonly when working with sc and remix in dev also happen in production. I'm not able to 100% validate that the errors stem from styled-components but i'm pretty confident. Also it's totally unpredictable when those occur. I have 2 out of ~15 colleges that can reproduce these stably on Chrome. I was not able to reproduce them at all. (Might be related to something like Network Speed, Performance of the Machine or Browser Extensions).

2. Causing unstyled content

When such a hydration error occurs, since Remix operates on the complete document, react throws away EVERYTHING and rebuilds the complete DOM from scratch.
Now styled components might be in a state where it already injected it's <style/> element into the <head /> of the document and won't re-check the presence of that when react re-builds the document. This creates a broken page where all styles from SC are missing.

Reach UI is not being actively maintained

The sad truth is that the library used in the examples is slowing down development reach/reach-ui#972 which means dependency issues that are already cropping up.

Will the examples be updated if ol' reliable goes down? I'd love to learn how to implement components with Radix or React Aria but I haven't had much luck after a full day of mud wrestling in Remix trying to make the switch.

For now it's an .npmrc file with legacy-peer-deps=true as I learned today the hard way.

Thank you so much! <3

No "working" styled-components example

What version of Remix are you using?

1.12.0

Are all your remix dependencies & dev-dependencies using the same version?

  • Yes

Steps to Reproduce

official styled-components example

Expected Behavior

That it will render both on first load as well as consecutive loads without err.

Actual Behavior

Exhibits the hydration issues mentioned here.
However, in our experience, the styles match fine on FIRST load. Only on page refresh do them become broken. Even with JS disabled this issue persists, which leads me to believe the issue is strictly an SSR one for the moment.

It does not appear that it will work with any SSR without the aid of babel-plugin-styled-components which itself is not supported in Remix since it doesn't seem we have access to plugins or modifying esbuild config.

As a comparison, Next.js allows you to control webpack option values from a configuration file (next.config.js) so they can implement the needed plugins. A member of the development team says in a PR comment that this is because exposing the configuration values would lock in the compiler's choices and also risk breaking the application.

This limitation seems to be leading some remix users to implement workarounds using a custom module to override esbuild.

Then there are a number of other mentions out there of similar issues that link around and I'm not even quite sure if its relates to the same hydration issue or not, but certainly sounds like it would affect the existing example.

There are even posts about how to do this with NextJS that say there are no issues.... but that seems odd when the example doesnt seem to need babel-plugin-styled-components.

@kentcdodds mentions a possible fix here using patch-package, however then @jmurzy mentions that the needed code is stripped out, rendering that possible fix incomplete.

For added injury, we also need to get Material-UI v4 working, which seems to have exactly the same issue. First load, all the style names match up, on reload, none match. This is also with JS disabled, so it appears again to be an SSR only issue.

Conclusion

None of the methods above seem to work for us, and we're currently not clear if its because we use pnpm or that it's a monorepo, or that we also implement our own custom react ui lib that also uses babel-plugin-styled-components but in any case, none seem to work.

We're VERY much wanting to migrate all our sites to Remix but need to slowly migrate away from styled-components, and not cold-turkey cut it off. So we need a migration path for styled-components with Remix.

Official Getting Started blog-tutorial not able to seed new Post โ€“ is this a bug?

I am following this tutorial, and everything was going well until I tried to seed the new Post model using npx prisma db seed:
https://remix.run/docs/en/v1/tutorials/blog

I have added

model Post {
  slug     String @id
  title    String
  markdown String

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

to prisma/schema.prisma, but it will not allow me to seed the new model to the schema. I have tried restarting VSCode, and deleting node_modules and rerunning npm install, but typescript is always unable to compile.

% npx prisma db push      
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": SQLite database "data.db" at "file:./data.db?connection_limit=1"

The database is already in sync with the Prisma schema.

โœ” Generated Prisma Client (4.3.1 | library) to ./node_modules/@prisma/client in 58ms`

`% npx prisma db seed
Environment variables loaded from .env
Running seed command `ts-node --require tsconfig-paths/register prisma/seed.ts` ...
../blog-tutorial/node_modules/ts-node/src/index.ts:859
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: โจฏ Unable to compile TypeScript:
prisma/seed.ts:81:18 - error TS2339: Property 'post' does not exist on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.

81     await prisma.post.upsert({
                    ~~~~

    at createTSError (/blog-tutorial/node_modules/ts-node/src/index.ts:859:12)
    at reportTSError (/blog-tutorial/node_modules/ts-node/src/index.ts:863:19)
    at getOutput (/blog-tutorial/node_modules/ts-node/src/index.ts:1077:36)
    at Object.compile (/blog-tutorial/node_modules/ts-node/src/index.ts:1433:41)
    at Module.m._compile (/blog-tutorial/node_modules/ts-node/src/index.ts:1617:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Object.require.extensions.<computed> [as .ts] (/blog-tutorial/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  diagnosticCodes: [ 2339 ]
}

An error occured while running the seed command:
Error: Command failed with exit code 1: ts-node --require tsconfig-paths/register prisma/seed.ts`

I am using Node v16.17.0and NPM v8.15.0.

I am stuck here, any ideas? Thanks

_official-realtime-app example is buggy

When I load the _official-realtime-app example on CodeSandbox, I notice that:

  • When viewing a single issue, even though it says, "That title is content editable and will save on blur," when I edit the title it just reverts back after a moment. (Edit: Also reproduces on my local machine.)

  • The back button in the integrated browser doesn't work. (Edit: Doesn't reproduce on my local machine, but pressing the back button takes almost a full second to go back to which is not great for a simple example project in a framework that purports to be very fast.)

Hydration issue with the Google Analytics example

If you put the <script> tags in a client-only wrapper, gtag never gets loaded/defined and gtag.pageview never fires:
image

If you follow the <script> embedding example from this repo's root.tsx file, hydration errors ensue:
image

Has anyone had any luck figuring out a way around this?

Stitches example: Greedy regexp pattern potentially breaks markup

Hi!

The stitches example uses a Regexp pattern to replace the style tag in SSR with the actual server side rendered styles.

However, the pattern used to do this is too greedy. I just had an example in which I have multiple additional style tags also in the the whole document body, which got all replaced until the last closing style tag.

By replacing .* with .*? I believe this issue should be fixed.

Additionally, also matching newlines by using the /s flag might avoid another issue in case the SSR stylesheet contains newlines, though I am unsure how much of an edge case this is.

styled-components example not updated

I start a new project with npx create-remix@latest command and my entry.server.tsx file has 111 lines of code.
Styled-components entry.server.tsx file has only 29 line of code.

Can you update that example?

The exemple code use return new Response("<!DOCTYPE html>" + markup, {
But last remix version use new PassThrough() has new body value:

          const body = new PassThrough();

          responseHeaders.set("Content-Type", "text/html");

          resolve(
            new Response(body, {
              headers: responseHeaders,
              status: didError ? 500 : responseStatusCode,
            })
          );

Followed Remix / Stitches Example and getting FOUC

What version of Remix are you using?

1.1.3

Steps to Reproduce

Visit https://california-custom-tile.netlify.app/ and notice shift of logo due to FOUC. I applied example project found here and am unable to resolve the flash of unstyled content. I originally followed this tutorial as it was the only writing I could find at the time tying Stitches and Remix together.

Here's all the relevant changes I made following the example.

Expected Behavior

Logo should NOT shift from left side to center from a flash of unstyled content (FOUC). Logo should be centered on load

Actual Behavior

Logo shifts from left side to right because of FOUC.

Official blog tutorial is not working

_official-blog-tutorial example is not working.

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: undefined@undefined
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^18.2.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0 || 17.x" from @reach/[email protected]
npm ERR! node_modules/@reach/alert
npm ERR!   @reach/alert@"^0.17.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 

Reach UI does not support React 18 yet (reach/reach-ui#916).

We can remove Reach UI dependency here and use any other thing that supports React 18. I can work on a fix if you agree to do so.

MSW example not working

The MSW example seem to not be working anymore.

This error appear in the front and on the server when we try to reach the home page after running

npm run dev
Application Error

FetchError: request to https://my-mock-api.com/ failed, reason: response3.headers.all is not a function
    at NodeClientRequest.<anonymous> (/****/examples/msw/node_modules/@remix-run/web-fetch/src/fetch.js:112:11)
    at NodeClientRequest.emit (node:events:517:28)
    at NodeClientRequest.emit (/****/examples/msw/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.ts:299:22)
    at /****/examples/msw/node_modules/@mswjs/interceptors/src/interceptors/ClientRequest/NodeClientRequest.ts:153:14

The codeSandbox link seem to also have the same error

BTW: my node version is v18.18.0

[Feature Request] Framework user wants to have an example integration with Cloudscape Design System

As a framework user I want to utilize Remix in conjunction with the Cloudscape Design System. To unterstand the basic integration details I want to have an example for that within remix-run/examples repository.

Acceptance Criteria

  • Example integration between Remix and Cloudscape Design System exists
  • Example intergration shows rendering of Cloudscape Design System components and related styles.

Background

I would like to integrate and use Cloudscape as the front-end component design system. Unfortunately I'm stuck with the example integration trying to follow both guides:
https://remix.run/docs/en/main/guides/styling
https://cloudscape.design/get-started/integration/using-cloudscape-components/
The example integration code is currently stored here - https://github.com/build-failure/remix-examples/tree/cloudscape/cloudscape. It can be tested within codesandbox.io - https://codesandbox.io/p/sandbox/github/build-failure/remix-examples/tree/cloudscape/cloudscape.
AFAIK Cloudscape is using CSS Side-Effect Imports, thus I followed the last integration scenario - https://remix.run/docs/en/main/guides/styling#css-side-effect-imports.
While the global styles are loaded properly, styles for the particular components are not loaded.
Additionally I'm receiving server side errors (can be viewed at https://codesandbox.io/p/sandbox/github/build-failure/remix-examples/tree/cloudscape/cloudscape):

Remix App Server started at http://localhost:3000/ (http://192.168.241.2:3000/)
Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for common fixes.
    at InternalContainer (/project/sandbox/build/index.js:899:9)
    at AnalyticsFunnelSubStep (/project/sandbox/build/index.js:938:33)
    at Container (/project/sandbox/build/index.js:952:9)
    at div
    at div
    at InternalSpaceBetween (/project/sandbox/build/index.js:996:9)
    at SpaceBetween (/project/sandbox/build/index.js:1006:9)
    at body
    at html
    at App (/project/sandbox/build/index.js:1638:55)
    at RemixRoute (/project/sandbox/node_modules/@remix-run/react/dist/components.js:71:3)
    at RenderedRoute (/project/sandbox/node_modules/react-router/dist/umd/react-router.development.js:680:7)
    at RenderErrorBoundary (/project/sandbox/node_modules/react-router/dist/umd/react-router.development.js:624:7)
    at Routes (/project/sandbox/node_modules/react-router/dist/umd/react-router.development.js:1174:7)
    at Router (/project/sandbox/node_modules/react-router/dist/umd/react-router.development.js:1106:17)
    at StaticRouterProvider (/project/sandbox/node_modules/react-router-dom/server.js:67:3)
    at RemixErrorBoundary (/project/sandbox/node_modules/@remix-run/react/dist/errorBoundaries.js:24:5)
    at RemixServer (/project/sandbox/node_modules/@remix-run/react/dist/server.js:47:3)

While there are proposals on how to fix that (https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85), I'm not sure how to achieve this...

Typecheck fails on blog-tutorial example

When I run typechecking or have my editor open, the following errors are shown by typescript, even on a fresh clone of the example:

> typecheck
> tsc -b && tsc -b cypress

app/routes/notes/$noteId.tsx:36:16 - error TS2352: Conversion of type 'SerializeObject<Simplify<{ note: Note; } & {}>>' to 
type 'LoaderData' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, conv
ert the expression to 'unknown' first.
  The types of 'note.createdAt' are incompatible between these types.
    Type 'string' is not comparable to type 'Date'.

36   const data = useLoaderData() as LoaderData;
                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

app/routes/posts/$slug.tsx:23:26 - error TS2352: Conversion of type 'SerializeObject<Simplify<{ post: Post; html: string; }
 & {}>>' to type 'LoaderData' may be a mistake because neither type sufficiently overlaps with the other. If this was inten
tional, convert the expression to 'unknown' first.
  The types of 'post.createdAt' are incompatible between these types.
    Type 'string' is not comparable to type 'Date'.

23   const { post, html } = useLoaderData() as LoaderData;
                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

app/routes/posts/admin.tsx:16:21 - error TS2352: Conversion of type 'SerializeObject<Simplify<{ posts: Post[]; } & {}>>' to
 type 'LoaderData' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, con
vert the expression to 'unknown' first.
  Types of property 'posts' are incompatible.
    Type 'SerializeObject<Simplify<{ createdAt: Date; updatedAt: Date; title: string; slug: string; markdown: string; } & {
}>>[]' is not comparable to type 'Post[]'.
      Type 'SerializeObject<Simplify<{ createdAt: Date; updatedAt: Date; title: string; slug: string; markdown: string; } &
 {}>>' is not comparable to type 'Post'.

16   const { posts } = useLoaderData() as LoaderData;
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

app/routes/posts/index.tsx:18:21 - error TS2352: Conversion of type 'SerializeObject<Simplify<{ posts: Post[]; } & {}>>' to
 type 'LoaderData' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, con
vert the expression to 'unknown' first.
  Types of property 'posts' are incompatible.
    Type 'SerializeObject<Simplify<{ createdAt: Date; updatedAt: Date; title: string; slug: string; markdown: string; } & {
}>>[]' is not comparable to type 'Post[]'.

18   const { posts } = useLoaderData() as LoaderData;
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Found 4 errors.

What seems to be happening is that createdAt is a string rather than a date somewhere in between (in Prisma, maybe). A temporary workaround is to convert the result of useLoaderData to unknown and then LoaderData, but this isn't the best solution. This problem happens regardless of the TS version (both 4.7 and 4.8 result in an error). Is there a known solution to this?

mdx-bundler example

Could someone add a mdx-bundler example? I'm having a hard time trying to use it with Remix.

Example for Vite + Styled Components??

The current example for Styled Components demonstrates using a custom handleRequest but with the introduction of Vite to the Remix ecosystem, this obviously deviates a bit from what we have right now. It would be great to have an example of how to get Styled Components set up similarly with Vite!

Using template as specified does not seem to work

tl;dr can we please update the readme to have template instructions that will work for an impatient noob?

Hello!

I'm new to remix and love it!

The examples are great but I had a tough time using one of the examples as a template.

Problem

In the readme I followed the instructions:

You can also initialize a new project with any of these examples using the --template flag of the create-remix CLI.

And used the example npx create-remix@latest --template examples/<example-dir>

Running this on my own, to use the socket.io example, I ran the following command:

npx create-remix@latest --template examples/socket.io

However, I received the following error:

๐Ÿšจ Invalid template selected. Please try again.

Solution

After reviewing the docs related to templates I experimented with a few possibilities.

These did not work for me:

npx create-remix@latest --template examples/main/socket.io
npx create-remix@latest --template remix-run/examples/blob/main/socket.io
npx create-remix@latest --template remix-run/examples/socket.io

Finally, using the full github path, this did work for me:

npx create-remix@latest --template https://github.com/remix-run/examples/tree/main/socket.io

My solution I believe is overly verbose than necessary, but if we can update the readme to have an example that will definitely run that would be great.

Thanks again for an amazing product!

Emotion example is poorly performant, re-rendering over 50 times a second

What version of Remix are you using?

1.2.3

Steps to Reproduce

  1. Download the example app:
$ svn export https://github.com/remix-run/remix/tree/main/examples/emotion
  1. Install dependencies
  2. Log style re-render trigger:
$ vim app/entry.client.tsx # Add `console.log("๐Ÿšจ RERENDER ๐Ÿšจ")` in `reset()` function body
  1. Run app:
$ npm run dev
  1. Look at the console:
    Browser console screenshot (clipped)

This is not only re-applying the style tags, but also re-rendering the entire app tree over 50 times a second, which isn't good at all. See my comment below for a suggestion on how to combat this problem.

Expected Behavior

A fast app

Actual Behavior

An app that is flooded with console warnings and re-renders

Blog Tutorial uses Route File Naming (v2)

The official Blog Tutorial instructs the reader to create a new Remix project using the command npx create-remix@latest --template remix-run/indie-stack blog-tutorial.

After this command is run, a project is created where remix.config.js contains this line: v2_routeConvention: true.

This results in a project that deviates slightly from the tutorial.

The index page in this project is not app/routes/index.tsx as referenced in the tutorial, but app/routes/_index.tsx.

The project uses flat routes as described on the page Route File Naming (v2).

Also, the reader of this tutorial needs to be aware of other changes to the routing, because of this. In the tutorial, the reader creates routes to the posts and admin pages that the reader needs to change:
app/routes/posts/index.tsx -> app/routes/posts._index.tsx
app/routes/posts/$slug.tsx -> app/routes/posts.$slug.tsx
app/routes/posts/admin.tsx -> app/routes/posts.admin.tsx
app/routes/posts/admin/index.tsx -> app/routes/posts.admin._index.tsx
app/routes/posts/admin/new.tsx -> app/routes/posts.admin.new.tsx

With these small changes, the app, as far as I have been able to determine, works as described in the tutorial.

The socket.io example does not show how to send messages from the server

It would be great to show how to send messages from the server in the socket.io example.

The reason it doesn't seem obvious to me is because the io server is defined in the server/index.js file which is a Javascript CommonJS file, but if for instance I want to broadcast a websocket message after doing a database update with Prisma, I would need to access this same io object from a Typescript ESModules file, and I have no idea how to do that.

Or if someone could nudge me in the right direction, I might be able to send a pull request.

_official-realtime-app Concurrent connections

First noted in my own project, but I can replicate the same issue in the _official-realtime-app.

It seems I can only have 6 tabs open at any given time (across clients). When I try and open a 7th tab, it hangs. Only when I close one of my other open tabs does its successfully load.

Commenting out the live reload hook allows me to open as many tabs as I wish.

Steps to reproduce:

  1. npm run build
  2. npm run start
  3. Open 6 tabs on localhost:3000.
    image
  4. Open a 7th tab. It will hang.
    image
  5. Close one the other tabs. The hanging tab will now successfully load.
    image

Upload Multiple files from input type files with attribute multiple

I am trying to upload multiple files from one input tag with the attribute multiple. How do i return the multiple files selected from the fileUploadHandler. I do not see any examples of this anywhere online. Only for one file! Thank you for the help!

import {
  json,
  LoaderArgs,
  unstable_parseMultipartFormData,
} from "@remix-run/node";
import { Form } from "@remix-run/react";
import { fileUploadHandler } from "~/fileUpload/index.server";

// import { fileUploadHandler } from "~/fileUpload/index.server";

// File for file Upload is in .server for bundle
// import {
//   unstable_composeUploadHandlers, unstable_createFileUploadHandler, unstable_createMemoryUploadHandler
// } from "@remix-run/node";

// export const fileUploadHandler = unstable_composeUploadHandlers(
//   unstable_createFileUploadHandler({
//     avoidFileConflicts: true,
//     file: ({ filename }) => filename,
//     maxPartSize: 5_000_000,
//   }),
//   unstable_createMemoryUploadHandler()
// );

export const meta = () => ({
  charset: "utf-8",
  title: "MultiFormTemplate",
  viewport: "width=device-width,initial-scale=1",
});

export let loader = async ({ request }: LoaderArgs) => null;

export async function action({ request }: ActionArgs) {
  const errors = {};
  const response = new Response();

  try {
    const form = await unstable_parseMultipartFormData(
      request,
      fileUploadHandler
    );
    const multipleFiles = form.get("multiple-files");
    const FirstName = form.get("FirstName");
    const values = {
      FirstName: FirstName,
    };
    // // validate the fields
    if (!FirstName) {
      errors.FirstName = "First name is required";
    }
    // return data if we have errors
    if (Object.keys(errors).length) {
      return json({ errors, values });
    }

    //How do i get multiple files here!! Only returns one!!
    console.log(multipleFiles);

    // else return the error
    return json(values, {
      status: 200,
      headers: { "Cache-Control": "no-store" },
    });
  } catch (errors) {
    console.log("errors", errors);
    return json({ errors }, { status: 500 });
  }
}

export default function MultiFormTemplate() {
  return (
    <div>
      <h4>MultiFormTemplate</h4>
      <Form method="post" encType="multipart/form-data">
        <input id="FirstName" name="FirstName" />
        <label htmlFor="multiple-files">Multiple Photos</label>
        <input type="file" id="multiple-files" name="multiple-files" multiple />
        <button type="submit">Submit</button>
      </Form>
    </div>
  );
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.