withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
47.25k stars 2.51k forks source link

Cannot find package 'cookie' - Vercel Adapter - hybrid and server outputs #9801

Open fabiobiondi opened 10 months ago

fabiobiondi commented 10 months ago

Astro Info

Astro                    v4.2.3
Node                     v18.17.1 (also tried with Node v20)
System                   macOS (arm64)
Package Manager          unknown
Output                   hybrid
Adapter                  @astrojs/vercel/serverless
Integrations             @astrojs/react
                         @astrojs/tailwind
                         @astrojs/mdx
                         @astrojs/sitemap

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

I have migrated a website from Astro v.1 (SSG) to v.4 (hybrid). There are hundred of images, dozens of markdown and more or less 200 Astro components.

Since I had some problems with the migration I decided to create a brand new project with v.4.2.3.

The astro.config.mjs is pretty simple:

import { defineConfig } from 'astro/config';
import vercelServerless from '@astrojs/vercel/serverless';
import react from "@astrojs/react";
import mdx from "@astrojs/mdx";

// https://astro.build/config
export default defineConfig({
  site: 'https://www.fabiobiondi.dev/',
  output: 'hybrid',
  adapter: vercelServerless(),

  integrations: [react(), mdx()],
});

Using Static Rendering: the build works fine in both, locally and deployed on Vercel ✅

Using hybrid output: • dev: works ✅ • production (Vercel) ❌: static pages work fine while when I open pages with export const prerender = false I got this error:

<< This Serverless Function has crashed. ...

This page just contains the following code:

---
export const prerender = false;
---
hello

Using server output: • dev: works ✅ • production (Vercel) ❌: all non-static pages have problems


This is the error I read from Vercel Logs, when I visit the SSR page:

undefined   ERROR   Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'cookie' imported from /var/task/.vercel/output/_functions/entry.mjs
    at new NodeError (node:internal/errors:405:5)
    at packageResolve (node:internal/modules/esm/resolve:895:9)
    at moduleResolve (node:internal/modules/esm/resolve:988:20)
    at moduleResolveWithNodePath (node:internal/modules/esm/resolve:939:12)
    at defaultResolve (node:internal/modules/esm/resolve:1181:79)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:835:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36) {
  code: 'ERR_MODULE_NOT_FOUND'

In the .vercel folder I see that the entry.mjs file cannot find the cookie library (but it's available in node_modules folder:

image

NOTE: I have also tried to install cookie on my project as dependency and peer Dependency

Have you some ideas or advice? Thank you 🙏

What's the expected result?

SSR pages should work on Vercel

Link to Minimal Reproducible Example

n/a

github-actions[bot] commented 10 months ago

Hello @fabiobiondi. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with needs repro will be closed if they have no activity within 3 days.

ematipico commented 10 months ago

Is cookie exported as an ESM module?

fabiobiondi commented 10 months ago

@ematipico Nope... CJS

image

I really don't understand what is happening. A blank hybrid project work fine. Now I have added re-created a project from scratch and it worked until I migrated a lot of content I have followed all the migration guides and everything works fine with SSG.

But a BLANK PAGE, with nothing else inside it, just a label, that use SSR instead, has that "cookie" problem!

I will try to create a minimal reproduction project...

lilnasy commented 10 months ago

Could you check whether "astro" is under "dependencies" and not "devDependencies"?

ematipico commented 10 months ago

Try vite.ssr.noExternal: ['cookie'] and see if this works for you

lilnasy commented 10 months ago

Due to a bug I introduced, the vercel serverless adapter does not set cookies but the cookie npm package does not present an issue.

Here is a deployed project that uses Astro.cookies.set("x", "y"), for example: https://basics-livid.vercel.app/

fabiobiondi commented 10 months ago

Could you check whether "astro" is under "dependencies" and not "devDependencies"?

Astro is located in dependencies, just as initially set by the Astro CLI. I move nothing 😅

fabiobiondi commented 10 months ago

Try vite.ssr.noExternal: ['cookie'] and see if this works for you

Just updated the astro.config.mjs but still doesn't work

export default defineConfig({
  site: 'https://www.fabiobiondi.dev/',
  output: 'hybrid',
  adapter: vercelServerless(),

  vite: {
    ssr: {
      noExternal: 'cookie'
    }
  },
  integrations: [react(), mdx()]
});
fabiobiondi commented 10 months ago

Due to a bug I introduced, the vercel serverless adapter does not set cookies but the cookie npm package does not present an issue. Here is a deployed project that uses Astro.cookies.set("x", "y"), for example: https://basics-livid.vercel.app/

I have deployed a basic project too without any problem. It works (a simple project like yours with SSR and SSG pages) But after adding some stuff I had these problems. I thought it was my fault or because of some custom configurations I did so I cleaned the astro config as you can see in my previous comment and just created a blank page (that don't use components or stuff) as shown below:

---
export const prerender = false;
---
hello

So I'm not able to reproduce the issue. Anyway this evening I will try to remove everything except for a couple of pages, hoping there will be the issue. And I will share the repo.

PS: i'm using Astro since version 1.x and created many websites, spoken to several conferences and so on.... so I'm not expert but I'm not a newbie either. So this behavior is very strange

PPS: I and some friend have another weird problem with Astro 4 and Vercel that we had never had but I'll open another issue about it. The CI doesn't work anymore as before: first Git pushes works fine but after a while (don't ask me the reason) we need to make a build locally and push it too in order to see the updates. But that's another story : )

lilnasy commented 10 months ago

Vercel's CI cache or commands could be interfering as well. You could test this by deleting .vercel and going through npm exec vercel deploy prompts to create a new project.

fabiobiondi commented 10 months ago

Try vite.ssr.noExternal: ['cookie'] and see if this works for you

I have tried this again and I have noticed I don't have the error on cookie anymore but on fast-glob, clsx, kleur

image

2024-01-24T20:56:43.151Z    undefined   ERROR   Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'kleur' imported from /var/task/.vercel/output/_functions/entry.mjs
    at new NodeError (node:internal/errors:405:5)
    at packageResolve (node:internal/modules/esm/resolve:895:9)
    at moduleResolve (node:internal/modules/esm/resolve:988:20)
    at moduleResolveWithNodePath (node:internal/modules/esm/resolve:939:12)
    at defaultResolve (node:internal/modules/esm/resolve:1181:79)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:835:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
INIT_REPORT Init Duration: 211.35 ms    Phase: init Status: error   Error Type: Runtime.ExitError
2024-01-24T20:56:43.413Z    undefined   ERROR   Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'kleur' imported from /var/task/.vercel/output/_functions/entry.mjs
    at new NodeError (node:internal/errors:405:5)
    at packageResolve (node:internal/modules/esm/resolve:895:9)
    at moduleResolve (node:internal/modules/esm/resolve:988:20)
    at moduleResolveWithNodePath (node:internal/modules/esm/resolve:939:12)
    at defaultResolve (node:internal/modules/esm/resolve:1181:79)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:835:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
INIT_REPORT Init Duration: 256.95 ms    Phase: invoke   Status: error   Error Type: Runtime.ExitError
Error: Runtime exited with error: exit status 1
fabiobiondi commented 10 months ago

Here a cleaned repository to reproduce the problem: https://github.com/fabiobiondi/fbsite_astro4

PAGES: ✅ SSG: https://fbsite-astro4.vercel.app/ ❌ SSR: https://fbsite-astro4.vercel.app/about

lilnasy commented 10 months ago

That is very unusual. The build did not complete. _functions is a temporary directory.

I am guessing the build completed successfully. I would expect vercel to not create a deployment otherwise. So what I think is happening here is @vercel/nft eating up continuations. Edit: no it isn't that.

For context, it is a library we use to manage node_modules for the deployment. I've had odd things happen to me during development. There are cases where it neither resolves nor rejects the promises it creates, which results in all code that awaits its result to simply never run and the process eventually exits with code 0.

I don't know how I would confirm this, however. Thanks for putting together a repro.

lilnasy commented 10 months ago

I looked into it again today and I couldn't reproduce it. Turns out the bug is sensitive to the package manager and OS.

With npm ``` mkdir repro-9801 cd repro-9801 git clone --depth 1 https://github.com/fabiobiondi/fbsite_astro4 . npm i npm exec astro build npx vercel deploy --prebuilt --prod ```
With pnpm ``` mkdir repro-9801 cd repro-9801 git clone --depth 1 https://github.com/fabiobiondi/fbsite_astro4 . pnpm i pnpm exec astro build npx vercel deploy --prebuilt --prod ```

I don't have a mac to test on. Do you know if it is any different with a different package manager? Are you deploying using vercel's github app?

bluwy commented 9 months ago

I released one for macos: ❌ https://astro-9801-pnpm-macos.vercel.app/about. I also got an error of: Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'kleur' imported from /var/task/.vercel/output/_functions/entry.mjs.

One thing I notice is that the conflicting dependencies are also dependencies of astro. While we do bundle astro with noExternal, its transitive deps are not bundled by Vite if they are also a dependency of the root Astro project (regardless of deps or devdeps, which could be problematic). However despite that, @verlel/nft should still bundled all the referenced node_modules files. For some reason they don't work.

From its deployment logs, it says "Downloading 46 deployment files...". And I can confirm that in .vercel it has 43 files, so they should be all included.

One hunch I have is that maybe the deps copied into .vercel were symlinked is the issue (pnpm). However, in the original issue description it's using npm so this doesn't seem like the issue. I'm very confused of what's going on.

EDIT: About the OSes, one thing we do know about Linux is that it's a case-sensitive fs. Though I'm unsure how that fits in the picture.

masaroli commented 9 months ago

I'm having the same issue what I was trying to do is to install vercel analytics

This config works:

import { defineConfig } from "astro/config";
import icon from "astro-icon";

// https://astro.build/config
export default defineConfig({
  integrations: [icon()],
  devToolbar: { enabled: false },
});

This throws the error:

import { defineConfig } from "astro/config";
import icon from "astro-icon";
import vercel from "@astrojs/vercel/serverless";

// https://astro.build/config
export default defineConfig({
  output: "server",
  integrations: [icon()],
  devToolbar: { enabled: false },
  adapter: vercel({
    webAnalytics: { enabled: true },
  }),
});
ProgrammerLP commented 9 months ago

Did anyone find a solution?

lilnasy commented 9 months ago

@masaroli If you have a static site, you might be able to use the static adapter instead.

import { defineConfig } from "astro/config";
import icon from "astro-icon";
- import vercel from "@astrojs/vercel/serverless";
+ import vercel from "@astrojs/vercel/static";

// https://astro.build/config
export default defineConfig({
-  output: "server",
+  output: "static", 
  integrations: [icon()],
  devToolbar: { enabled: false },
  adapter: vercel({
    webAnalytics: { enabled: true },
  }),
});

@ProgrammerLP Unfortunately, not. You can make it so that the SSR App depends less on node_modules using a vite config mentioned earlier in this thread, but not all NPM packages can be "inlined" that way. The bug itself is difficult to investigate since it only occurs on vercel's servers where there's not as much observability as to what's going on, and there's no way to run made-for-Vercel apps locally.

ProgrammerLP commented 9 months ago

Ah ok, thank you So we have to wait for a fix from vercels side

flamaso commented 8 months ago

i have the same problem. ✅ local ❌ vercel i get this only on vercel:

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'cookie' imported from /var/task/.vercel/output/_functions/entry.mjs at packageResolve (node:internal/modules/esm/resolve:858:9) at moduleResolve (node:internal/modules/esm/resolve:915:20) at moduleResolveWithNodePath (node:internal/modules/esm/resolve:1135:12) at defaultResolve (node:internal/modules/esm/resolve:1178:79) at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:396:12) at ModuleLoader.resolve (node:internal/modules/esm/loader:365:25) at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:240:38) at ModuleWrap. (node:internal/modules/esm/module_job:85:39) at link (node:internal/modules/esm/module_job:84:36) { code: 'ERR_MODULE_NOT_FOUND' } INIT_REPORT Init Duration: 260.46 ms Phase: invoke Status: error Error Type: Runtime.ExitError Error: Runtime exited with error: exit status 1

0x0m0t0 commented 8 months ago

I had this same problem recently, removing the .vercel/ folder cleared the issue for me.

FueRobertHer commented 8 months ago

Setting the node version on vercel to match my local env was what worked for me. Locally I was on v20 but on vercel it was previously set to v16. The error got resolved after updating the vercel setting to use v20.

JosueVanegas commented 7 months ago

This worked, just delete the vercel folder and make a commit and push to your repository and in the deploy vercel will take care of the rest

so basically that's how it's solved

  1. delete the vercel folder 2.deploy to vercel 3.vercel will do his thing

package.json "dependencies": { "@astrojs/check": "^0.5.10", "@astrojs/vercel": "^7.5.3", "astro": "^4.5.9", "resend": "^3.2.0", }

astro.config.mjs ` import { defineConfig } from "astro/config";

import vercel from "@astrojs/vercel/serverless";

// https://astro.build/config export default defineConfig({ output: "server", adapter: vercel(), });`

alannnn-estrada commented 5 months ago

If you have the .vercel folder locally in your project and you get the error "This Serverless Function has crashed", delete the folder and immediately do a commit and push. With that I could solve the problem. 👍

ruizdiazever commented 3 months ago

Same problema, it is only possible to deploy to the Vercel CLI and not automatically.

ruizdiazever commented 1 month ago

If you read the README.txt inside of .vercel:

Why do I have a folder named ".vercel" in my project? The ".vercel" folder is created when you link a directory to a Vercel project.

What does the "project.json" file contain? The "project.json" file contains:

  • The ID of the Vercel project that you linked ("projectId")
  • The ID of the user or team your Vercel project is owned by ("orgId")

Should I commit the ".vercel" folder? No, you should not share the ".vercel" folder with anyone. Upon creation, it will be automatically added to your ".gitignore" file.

ruizdiazever commented 1 month ago

In my case I solved it by adding the following files to .gitignore

bun.lockb
pnpm-lock.yml
package-lock.json
shoaibkh4n commented 1 day ago

hey guys, I think I found the solution and its working for me too. https://vercel.com/guides/serverless-function-contains-invalid-runtime-error

Just remove the .vercel folder from your local and downgrade the deployment node version from latest 22x to 18x. It will start working. image

@ematipico I think you can close this issue now 👀

ascorbic commented 1 hour ago

@shoaibkh4n It's good that you have a workaround, but downgrading Node isn't a fix. I think this is likely to be a bug in @vercel/nft. I'd be interested to see if this is still present in the beta version of Astro and the Vercel adapter