Commit 7b63053c authored by Zack Tanner's avatar Zack Tanner

'use server' should error when used in pages dir

parent 9a87d207
...@@ -31,6 +31,12 @@ use swc_core::{ ...@@ -31,6 +31,12 @@ use swc_core::{
use super::{cjs_finder::contains_cjs, import_analyzer::ImportMap}; use super::{cjs_finder::contains_cjs, import_analyzer::ImportMap};
use crate::FxIndexMap; use crate::FxIndexMap;
static NODE_MODULES_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"node_modules[\\/]").unwrap());
fn is_from_node_modules(filepath: &str) -> bool {
NODE_MODULES_RE.is_match(filepath)
}
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
#[serde(untagged)] #[serde(untagged)]
pub enum Config { pub enum Config {
...@@ -82,6 +88,7 @@ enum RSCErrorKind { ...@@ -82,6 +88,7 @@ enum RSCErrorKind {
NextRscErrServerImport((String, Span)), NextRscErrServerImport((String, Span)),
NextRscErrClientImport((String, Span)), NextRscErrClientImport((String, Span)),
NextRscErrClientDirective(Span), NextRscErrClientDirective(Span),
NextRscErrServerDirective(Span),
NextRscErrReactApi((String, Span)), NextRscErrReactApi((String, Span)),
NextRscErrErrorFileServerComponent(Span), NextRscErrErrorFileServerComponent(Span),
NextRscErrClientMetadataExport((String, Span)), NextRscErrClientMetadataExport((String, Span)),
...@@ -281,6 +288,13 @@ fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorK ...@@ -281,6 +288,13 @@ fn report_error(app_dir: &Option<PathBuf>, filepath: &str, error_kind: RSCErrorK
.to_string(), .to_string(),
vec![span], vec![span],
), ),
RSCErrorKind::NextRscErrServerDirective(span) => (
"You're using the \"use server\" directive in the pages/ directory. That only works in the app/ directory (App Router). \
Read more: \
https://nextjs.org/docs/app/building-your-application/rendering/server-components"
.to_string(),
vec![span],
),
RSCErrorKind::NextRscErrServerImport((source, span)) => { RSCErrorKind::NextRscErrServerImport((source, span)) => {
let msg = match source.as_str() { let msg = match source.as_str() {
// If importing "react-dom/server", we should show a different error. // If importing "react-dom/server", we should show a different error.
...@@ -411,6 +425,32 @@ fn collect_top_level_directives_and_imports( ...@@ -411,6 +425,32 @@ fn collect_top_level_directives_and_imports(
filepath, filepath,
RSCErrorKind::RedundantDirectives(expr_stmt.span), RSCErrorKind::RedundantDirectives(expr_stmt.span),
); );
} else if !is_from_node_modules(filepath) {
// `use server` directive is only allowed in app directory.
// Skip this check for node_modules files as they may be
// external
// server action libraries used by app directory code.
let is_app_dir = app_dir
.as_ref()
.map(|app_dir| {
if let Some(app_dir) = app_dir.as_os_str().to_str()
{
filepath.starts_with(app_dir)
} else {
false
}
})
.unwrap_or_default();
if !is_app_dir {
report_error(
app_dir,
filepath,
RSCErrorKind::NextRscErrServerDirective(
expr_stmt.span,
),
);
}
} }
} }
} }
...@@ -664,11 +704,6 @@ impl ReactServerComponentValidator { ...@@ -664,11 +704,6 @@ impl ReactServerComponentValidator {
} }
} }
fn is_from_node_modules(&self, filepath: &str) -> bool {
static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"node_modules[\\/]").unwrap());
RE.is_match(filepath)
}
fn is_callee_next_dynamic(&self, callee: &Callee) -> bool { fn is_callee_next_dynamic(&self, callee: &Callee) -> bool {
match callee { match callee {
Callee::Expr(expr) => self.imports.is_import(expr, "next/dynamic", "default"), Callee::Expr(expr) => self.imports.is_import(expr, "next/dynamic", "default"),
...@@ -715,8 +750,7 @@ impl ReactServerComponentValidator { ...@@ -715,8 +750,7 @@ impl ReactServerComponentValidator {
} }
fn assert_server_graph(&self, imports: &[ModuleImports], module: &Module) { fn assert_server_graph(&self, imports: &[ModuleImports], module: &Module) {
// If the if is_from_node_modules(&self.filepath) {
if self.is_from_node_modules(&self.filepath) {
return; return;
} }
for import in imports { for import in imports {
...@@ -738,7 +772,7 @@ impl ReactServerComponentValidator { ...@@ -738,7 +772,7 @@ impl ReactServerComponentValidator {
} }
fn assert_server_filename(&self, module: &Module) { fn assert_server_filename(&self, module: &Module) {
if self.is_from_node_modules(&self.filepath) { if is_from_node_modules(&self.filepath) {
return; return;
} }
static RE: Lazy<Regex> = static RE: Lazy<Regex> =
...@@ -768,7 +802,7 @@ impl ReactServerComponentValidator { ...@@ -768,7 +802,7 @@ impl ReactServerComponentValidator {
} }
fn assert_client_graph(&self, imports: &[ModuleImports]) { fn assert_client_graph(&self, imports: &[ModuleImports]) {
if self.is_from_node_modules(&self.filepath) { if is_from_node_modules(&self.filepath) {
return; return;
} }
for import in imports { for import in imports {
...@@ -801,7 +835,7 @@ impl ReactServerComponentValidator { ...@@ -801,7 +835,7 @@ impl ReactServerComponentValidator {
} }
fn assert_invalid_api(&self, module: &Module, is_client_entry: bool) { fn assert_invalid_api(&self, module: &Module, is_client_entry: bool) {
if self.is_from_node_modules(&self.filepath) { if is_from_node_modules(&self.filepath) {
return; return;
} }
static RE: Lazy<Regex> = static RE: Lazy<Regex> =
......
...@@ -100,14 +100,14 @@ fn react_server_components_errors(input: PathBuf) { ...@@ -100,14 +100,14 @@ fn react_server_components_errors(input: PathBuf) {
syntax(), syntax(),
&|tr| { &|tr| {
server_components( server_components(
FileName::Real(PathBuf::from("/some-project/src/page.js")).into(), FileName::Real(PathBuf::from("/some-project/app/page.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer, is_react_server_layer,
cache_components_enabled, cache_components_enabled,
use_cache_enabled, use_cache_enabled,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, Some(PathBuf::from("/some-project/app")),
) )
}, },
&input, &input,
...@@ -159,7 +159,7 @@ fn react_server_actions_errors(input: PathBuf) { ...@@ -159,7 +159,7 @@ fn react_server_actions_errors(input: PathBuf) {
use_cache_enabled: true, use_cache_enabled: true,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, Some(PathBuf::from("/app")),
), ),
server_actions( server_actions(
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
...@@ -223,7 +223,7 @@ fn use_cache_not_allowed(input: PathBuf) { ...@@ -223,7 +223,7 @@ fn use_cache_not_allowed(input: PathBuf) {
use_cache_enabled: false, use_cache_enabled: false,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, Some(PathBuf::from("/app")),
), ),
server_actions( server_actions(
&FileName::Real("/app/item.js".into()), &FileName::Real("/app/item.js".into()),
......
x You're importing a component that needs "next/root-params". That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/app/building- x You're importing a component that needs "next/root-params". That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.
| your-application/rendering/server-components | Learn more: https://nextjs.org/docs/app/building-your-application/rendering
| |
| |
,-[input.js:9:1] ,-[input.js:9:1]
......
x You're importing a component that needs "server-only". That only works in a Server Component which is not supported in the pages/ directory. Read more: https://nextjs.org/docs/app/building-your- x You're importing a component that needs "server-only". That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.
| application/rendering/server-components | Learn more: https://nextjs.org/docs/app/building-your-application/rendering
| |
| |
,-[input.js:9:1] ,-[input.js:9:1]
......
...@@ -448,14 +448,14 @@ fn react_server_components_typescript(input: PathBuf) { ...@@ -448,14 +448,14 @@ fn react_server_components_typescript(input: PathBuf) {
Syntax::Typescript(Default::default()), Syntax::Typescript(Default::default()),
&|tr| { &|tr| {
server_components( server_components(
FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(), FileName::Real(PathBuf::from("/some-project/app/some-file.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer: true, is_react_server_layer: true,
cache_components_enabled: false, cache_components_enabled: false,
use_cache_enabled: false, use_cache_enabled: false,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, Some(PathBuf::from("/some-project/app")),
) )
}, },
&input, &input,
...@@ -476,14 +476,14 @@ fn react_server_components_fixture(input: PathBuf) { ...@@ -476,14 +476,14 @@ fn react_server_components_fixture(input: PathBuf) {
syntax(), syntax(),
&|tr| { &|tr| {
server_components( server_components(
FileName::Real(PathBuf::from("/some-project/src/some-file.js")).into(), FileName::Real(PathBuf::from("/some-project/app/some-file.js")).into(),
Config::WithOptions(Options { Config::WithOptions(Options {
is_react_server_layer, is_react_server_layer,
cache_components_enabled: false, cache_components_enabled: false,
use_cache_enabled: false, use_cache_enabled: false,
}), }),
tr.comments.as_ref().clone(), tr.comments.as_ref().clone(),
None, Some(PathBuf::from("/some-project/app")),
) )
}, },
&input, &input,
......
/* __next_internal_client_entry_do_not_use__ cjs */ const { createProxy } = require("private-next-rsc-mod-ref-proxy"); /* __next_internal_client_entry_do_not_use__ cjs */ const { createProxy } = require("private-next-rsc-mod-ref-proxy");
module.exports = createProxy("/some-project/src/some-file.js"); module.exports = createProxy("/some-project/app/some-file.js");
// This is a comment. // This is a comment.
/* __next_internal_client_entry_do_not_use__ default,a,b,c,*,f auto */ const { createProxy } = require("private-next-rsc-mod-ref-proxy"); /* __next_internal_client_entry_do_not_use__ default,a,b,c,*,f auto */ const { createProxy } = require("private-next-rsc-mod-ref-proxy");
module.exports = createProxy("/some-project/src/some-file.js"); module.exports = createProxy("/some-project/app/some-file.js");
...@@ -380,6 +380,68 @@ describe('Error Overlay for server components compiler errors in pages', () => { ...@@ -380,6 +380,68 @@ describe('Error Overlay for server components compiler errors in pages', () => {
} }
}) })
test("using 'use server' directive in pages", async () => {
await using sandbox = await createSandbox(next, initialFiles)
const { session } = sandbox
await session.patch(
'components/Comp.js',
outdent`
'use server'
export default function Comp() {
return <p>hello world</p>
}
`
)
await session.assertHasRedbox()
await expect(session.getRedboxSource()).resolves.toMatch(
/That only works in the app\/ directory \(App Router\)/
)
if (process.env.IS_TURBOPACK_TEST) {
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./components/Comp.js (1:1)
Ecmascript file had an error
> 1 | 'use server'
| ^^^^^^^^^^^^
2 |
3 | export default function Comp() {
4 | return <p>hello world</p>
You're using the "use server" directive in the pages/ directory. That only works in the app/ directory (App Router). Read more: https://nextjs.org/docs/app/building-your-application/rendering/server-components
Import traces:
Browser:
./components/Comp.js
./pages/index.js
SSR:
./components/Comp.js
./pages/index.js"
`)
} else {
expect(next.normalizeTestDirContent(await session.getRedboxSource()))
.toMatchInlineSnapshot(`
"./components/Comp.js
Error: x You're using the "use server" directive in the pages/ directory. That only works in the app/ directory (App Router). Read more: https://nextjs.org/docs/app/building-your-application/rendering/server-components
,-[1:1]
1 | 'use server'
: ^^^^^^^^^^^^
2 |
3 | export default function Comp() {
4 | return <p>hello world</p>
\`----
Import trace for requested module:
./components/Comp.js
./pages/index.js"
`)
}
})
describe("importing 'next/cache' APIs in pages", () => { describe("importing 'next/cache' APIs in pages", () => {
test.each([ test.each([
'revalidatePath', 'revalidatePath',
......
import { nextTestSetup } from 'e2e-utils'
import { assertNoRedbox, retry } from 'next-test-utils'
describe('app-dir - action-in-pages-router', () => {
const { next, isNextStart } = nextTestSetup({
files: __dirname,
})
it('should not error on fake server action in pages router', async () => {
const browser = await next.browser('/foo')
const button = await browser.elementByCss('button')
await button.click()
await retry(async () => {
const browserLogText = (await browser.log())
.map((item) => item.message)
.join('')
// This is a fake server action, a simple function so it can still work
expect(browserLogText).toContain('action:foo')
await assertNoRedbox(browser)
})
})
if (isNextStart) {
// Disabling for turbopack because the chunk path are different
if (!process.env.IS_TURBOPACK_TEST) {
it('should not contain server action in page bundle', async () => {
const pageBundle = await next.readFile('.next/server/pages/foo.js')
// Should not contain the RSC client import source for the server action
expect(pageBundle).not.toContain('react-server-dom-webpack/client')
})
}
it('should not contain server action in manifest', async () => {
if (process.env.IS_TURBOPACK_TEST) {
const manifest = JSON.parse(
await next.readFile('.next/server/server-reference-manifest.json')
)
expect(Object.keys(manifest.node).length).toBe(0)
} else {
expect(
await next.hasFile('.next/server/server-reference-manifest.json')
).toBe(false)
}
})
}
})
'use server'
export async function actionFoo() {
return 'action:foo'
}
import { actionFoo } from '../actions'
export default function Page() {
return (
<button
onClick={() => {
actionFoo().then((v) => console.log(v))
}}
>
hello
</button>
)
}
// Keep route as dynamic
export async function getServerSideProps() {
return { props: {} }
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment