ModuleNotFoundError: Module not found: Error: Can't resolve 'next/server' - node.js

I just cloned the Next Auth Example, changed ports in package.json to match my server and added my domain in .env.local. Because of WASM middleware in Next 12, I had to downgrade to Next 11, so I just edited package.json to "next": "^11.1.3" and ran npm i again.
When I try to npm run build, I get this error:
ModuleNotFoundError: Module not found: Error: Can't resolve 'next/server' in 'domain.com/pages'
The npm run dev works fine.
The page that has the server import is:
https://github.com/nextauthjs/next-auth-example/blob/main/pages/_middleware.js
import { getToken } from "next-auth/jwt"
import { NextResponse } from "next/server"
/** #param {import("next/server").NextRequest} req */
export async function middleware(req) {
if (req.nextUrl.pathname === "/middleware-protected") {
const session = await getToken({
req,
secret: process.env.SECRET,
secureCookie:
process.env.NEXTAUTH_URL?.startsWith("https://") ??
!!process.env.VERCEL_URL,
})
// You could also check for any property on the session object,
// like role === "admin" or name === "John Doe", etc.
if (!session) return NextResponse.redirect("/api/auth/signin")
// If user is authenticated, continue.
}
}
Full Log:
> next-auth-example#0.0.0 build /domain.com
> next build
info - Loaded env from /domain.com/.env.local
info - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
info - Checking validity of types
warn - No ESLint configuration detected. Run next lint to begin setup
info - Creating an optimized production build
Failed to compile.
ModuleNotFoundError: Module not found: Error: Can't resolve 'next/server' in 'domain.com/pages'
> Build error occurred
Error: > Build failed because of webpack errors
at domain.com/node_modules/next/dist/build/index.js:397:19
at async Span.traceAsyncFn (domain.com/node_modules/next/dist/telemetry/trace/trace.js:60:20)
at async Object.build [as default] (domain.com/node_modules/next/dist/build/index.js:77:25)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! next-auth-example#0.0.0 build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the next-auth-example#0.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! domain.com/.npm/_logs/blahblahblah-debug.log // I edited this line
package.json
{
"name": "authentication",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"author": "damn",
"license": "ISC",
"dependencies": {
"next": "^11.1.2",
"next-auth": "^4.1.2",
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
}
(removed -p since it had no effect in my environment)
What's causing the problem and how should I solve it?

Middleware as a concept was introduced with NextJS 12 - See here - https://nextjs.org/blog/next-12#introducing-middleware
For your usecase, see here and follow the api routes example.

Related

How to fix NPM EJSONParse with this package.json file?

when I try the command npm install I have this
C:\Users\khaou>npm install
npm ERR! code EJSONPARSE
npm ERR! path C:\Users\khaou/package.json
npm ERR! JSON.parse Unexpected end of JSON input while parsing empty string
npm ERR! JSON.parse Failed to parse JSON data.
npm ERR! JSON.parse Note: package.json must be actual JSON, not just JavaScript.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\khaou\AppData\Local\npm-cache\_logs\2021-12-31T16_42_25_903Z-debug.log
This is the JSON:
{
"name": "eth-todo-list",
"version": "1.0.0",
"description": "Blockchain Todo List Powered By Ethereum",
"main": "truffle-config.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && sexit 1"
},
"author": "gregory#dappuniversity.com",
"license": "ISC",
"devDependencies": {
"bootstrap": "4.1.3",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"chai-bignumber": "^2.0.2",
"lite-server": "^2.3.0",
"nodemon": "^1.17.3",
"truffle": "5.0.2",
"truffle-contract": "3.0.6"
}
}
Probably your file association is other than JavaScript like JavaScript react or any other.
Check your package.json settings file to have Item:javascript Value:javascript as default extension (*) on Files:Associations.
package.json->file->preferences->settings->Files:Associations
Item:javascript Value:javascript
Hope it works!

I have created a new project with ANGULAR 12, I am trying to add Jest.js to

I have created a new project with ANGULAR 12, I am trying to add Jest.js to this project, but I get the next error.
TypeError: Jest: a transform must export something.
at D:\Refraccion\SOFTWARE----\TDD and DBB\demo1\node_modules\#jest\transform\build\ScriptTransformer.js:386:19
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Promise.all (index 0)
at async ScriptTransformer.loadTransformers (D:\Refraccion\SOFTWARE----\TDD and DBB\demo1\node_modules\#jest\transform\build\ScriptTransformer.js:378:5)
at async createScriptTransformer (D:\Refraccion\SOFTWARE----\TDD and DBB\demo1\node_modules\#jest\transform\build\ScriptTransformer.js:1106:3)
at async D:\Refraccion\SOFTWARE----\TDD and DBB\demo1\node_modules\#jest\core\build\TestScheduler.js:269:31
at async Promise.all (index 0)
at async TestScheduler.scheduleTests (D:\Refraccion\SOFTWARE----\TDD and DBB\demo1\node_modules\#jest\core\build\TestScheduler.js:262:5)
at async runJest (D:\Refraccion\SOFTWARE----\TDD and DBB\demo1\node_modules\#jest\core\build\runJest.js:387:19)
at async _run10000 (D:\Refraccion\SOFTWARE----\TDD and DBB\demo1\node_modules\#jest\core\build\cli\index.js:408:7)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! demo1#0.0.0 test: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the demo1#0.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Tom\AppData\Roaming\npm-cache\_logs\2021-06-06T22_50_07_345Z-debug.log
jest.config.js
module.exports = {
moduleNameMapper: {
'#core/(.*)': '<rootDir>/src/app/core/$1',
},
preset: 'jest-preset-angular',
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
};
package.json
{
"name": "demo1",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"test": "jest",
}
}
Is there some way to fix it in ANGULAR?
Experienced the same thing when I tried to create a new project, so far it isn't compatible with the newest Angular 12 yet that I know of.

Postinstall of module is executed before postinstall of sub-module

Edit:
I'm asking how to install it from GitHub, not npm, that the question.
In case you want to know why: I'm working on some private projects and don't what t publish the code. This leads to the code being in a private repository, not published on npm.
Original post:
Trying to install a module from GitHub (it is in typescript, thus I need a compilation script [postinstall]). It seems to fail because one of the module dependencies is also on GitHub, and that postinstall script is not waited on by the current postinstall script.
Old GitHub issue that sounds related: https://github.com/npm/npm/issues/5001
Yes, like the issue, I also use the same dependency in the main project as the module does.
Program
Version
node
v16.1.0
npm
7.11.2
npm info run newton#1.0.1 postinstall node_modules/newton tsc -d -p .
npm info run nodemon#2.0.7 postinstall node_modules/nodemon node bin/postinstall || exit 0
npm info run rendery#2.0.0 postinstall node_modules/rendery tsc -d -p .
npm info run nodemon#2.0.7 postinstall { code: 0, signal: null }
npm timing build:run:postinstall:node_modules/nodemon Completed in 157ms
npm info run newton#1.0.1 postinstall { code: 0, signal: null }
npm timing build:run:postinstall:node_modules/newton Completed in 2409ms
npm info run rendery#2.0.0 postinstall { code: 2, signal: null }
npm timing reify:rollback:createSparse Completed in 2864ms
npm timing reify:rollback:retireShallow Completed in 0ms
npm timing command:install Completed in 47807ms
npm verb stack Error: command failed
npm verb stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\#npmcli\promise-spawn\index.js:64:27)
npm verb stack at ChildProcess.emit (node:events:365:28)
npm verb stack at maybeClose (node:internal/child_process:1067:16)
npm verb stack at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
npm verb pkgid rendery#2.0.0
npm verb cwd C:\Users\Elias\git\natrias
npm verb Windows_NT 10.0.19043
npm verb argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "i" "--verbose" "--force"
npm verb node v16.1.0
npm verb npm v7.11.2
npm ERR! code 2
npm ERR! path C:\Users\Elias\git\natrias\node_modules\rendery
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c tsc -d -p .
npm ERR! src/2d/CanvasRenderyContext2D.ts(1,29): error TS2307: Cannot find module 'newton/2d/ReadonlyVector2' or its corresponding type declarations.
npm ERR! src/2d/CanvasRenderyContext2D.ts(2,21): error TS2307: Cannot find module 'newton/2d/Vector2' or its corresponding type declarations.
npm ERR! src/2d/ReadonlyRenderyContext2D.ts(1,29): error TS2307: Cannot find module 'newton/2d/ReadonlyVector2' or its corresponding type declarations.
npm ERR! src/2d/RenderyContext2D.ts(1,29): error TS2307: Cannot find module 'newton/2d/ReadonlyVector2' or its corresponding type declarations.
npm verb exit 2
npm timing npm Completed in 48318ms
npm verb code 2
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Elias\AppData\Local\npm-cache\_logs\2021-05-12T16_19_34_975Z-debug.log
Note that rendery postinstall starts before newton postinstall completes.
Newton package.json
{
"name": "newton",
"version": "1.0.1",
"description": "",
"scripts": {
"lint": "eslint '*/**/*.ts'",
"lint:fix": "eslint '*/**/*.ts' --fix",
"postinstall": "tsc -d -p .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.22.0",
"#typescript-eslint/parser": "^4.22.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0"
},
"dependencies": {
"typescript": "^4.2.4"
}
}
Rendery package.json
{
"name": "rendery",
"version": "2.0.0",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "eslint '*/**/*.ts'",
"lint:fix": "eslint '*/**/*.ts' --fix",
"postinstall": "tsc -d -p ."
},
"keywords": [],
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.22.0",
"#typescript-eslint/parser": "^4.22.0",
"eslint": "^7.25.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-typescript-sort-keys": "^1.6.0"
},
"dependencies": {
"newton": "github:Elias-Graf/newton#main",
"typescript": "^4.2.4"
}
}
It's not a good practice to publish unbuilt packages. I recommend changing the postinstall script into a prepare script so it builds the package before publishing it.
{
"name": "newton",
"version": "1.0.1",
"description": "",
"scripts": {
"lint": "eslint '*/**/*.ts'",
"lint:fix": "eslint '*/**/*.ts' --fix",
"prepare": "tsc -d -p .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.22.0",
"#typescript-eslint/parser": "^4.22.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0"
},
"dependencies": {
"typescript": "^4.2.4"
}
}
{
"name": "rendery",
"version": "2.0.0",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "eslint '*/**/*.ts'",
"lint:fix": "eslint '*/**/*.ts' --fix",
"prepare": "tsc -d -p ."
},
"keywords": [],
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^4.22.0",
"#typescript-eslint/parser": "^4.22.0",
"eslint": "^7.25.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"eslint-plugin-typescript-sort-keys": "^1.6.0"
},
"dependencies": {
"newton": "github:Elias-Graf/newton#main",
"typescript": "^4.2.4"
}
}
This would fix your issue.

Error in starting the lite-server using NPM

npm ERR! code EJSONPARSE
npm ERR! file C:\Users\thehitmanranjan\Desktop\git-test\package.json
npm ERR! JSON.parse Failed to parse json
npm ERR! JSON.parse Unexpected string in JSON at position 240 while
parsing '{
npm ERR! JSON.parse "name": "git-test",
npm ERR! JSON.parse "version": "1.'
npm ERR! JSON.parse Failed to parse package.json data.
npm ERR! JSON.parse package.json must be actual JSON, not just
JavaScript.
This is the error I get when I give command "npm start".
My package.JSON file has the following contents:
{
"name": "git-test",
"version": "1.0.0",
"description": "\"This is a test directory to learn Git and Node\"",
"main": "index.html",
"scripts": {
"start":"npm run lite",
"test": "echo \"Error: no test specified\" && exit 1"
"lite":"lite-server"
},
"repository": {
"type": "git",
"url": "git+https://github.com/thehitmanranjan/git-test.git"
},
"author": "Pratik Ranjan",
"license": "ISC",
"bugs": {
"url": "https://github.com/thehitmanranjan/git-test/issues"
},
"homepage": "https://github.com/thehitmanranjan/git-test#readme",
"devDependencies": {
"lite-server": "^2.5.4"
}
}
There is a comma missing after this line "test": "echo \"Error: no test specified\" && exit 1"
Also, if that doesn't work, try renaming your package.json to package.json.old and re-doing npm init. It solved my problem. I was going crazy for hours trying to figure it out.

ReactJS Server-Side Babel-Core PNG error

The situation:
I've built a web app with ReactJS full client-side. It is working great.
My desire:
Change my app to render from server-side.
The problem:
I'm facing problems to precompile with babel due some .png file.
package.json
{
"name": "web.facundolarocca.com",
"version": "0.1.0",
"private": true,
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.11.0",
"react-scripts": "0.8.4"
},
"dependencies": {
"body-parser": "^1.16.0",
"config": "^1.24.0",
"express": "^4.14.0",
"no-if-validator": "^1.0.0-4",
"nodemailer": "^2.7.0",
"nodemailer-smtp-transport": "^2.7.2",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-redux": "^5.0.4",
"react-responsive": "^1.2.6",
"react-router": "^4.1.1",
"react-router-dom": "^4.1.1",
"react-scroll": "^1.5.2",
"redux": "^3.6.0",
"redux-thunk": "^2.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"start:dev": "babel-node server/server.js",
"start:dev:nodemon": "nodemon server/server.js --exec babel-node",
"build:prod": "babel server/server.js -d build-server",
"server:start": "node build-server/server.js"
},
"standard": {
"global": [
"it"
]
}
}
Server route
import React from 'react'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import { renderToString } from 'react-dom/server'
import { BrowserRouter } from 'react-router-dom'
import reducer from '../src/reducers/index'
import App from '../src/containers/App'
// server.use('/', express.static(path.join(__dirname, '../build')))
server.use('/', (req, res) => {
const store = createStore(
reducer,
applyMiddleware(
thunkMiddleware
)
)
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
)
// Grab the initial state from our Redux store
const preloadedState = store.getState()
// Send the rendered page back to the client
res.send(renderFullPage(html, preloadedState))
})
let renderFullPage = (html, preloadedState) => {
return `
<!doctype html>
<html>
<head>
<title>Redux Universal Example</title>
</head>
<body>
<div id="root">${html}</div>
<script>
// WARNING: See the following for security issues around embedding JSON in HTML:
// http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
<script src="/static/bundle.js"></script>
</body>
</html>
`
}
Console error:
SyntaxError:
C:/.../src/images/background.png:
Unexpected character '�' (1:0) [0m[31m[1m>[22m[39m[90m 1 |
[39m�PNG [90m | [39m[31m[1m^[22m[39m [90m 2 |
[39m[37m[41m[1m[22m[49m[39m [90m 3 | [39m[37m[41m[1m
npm ERR! Windows_NT 10.0.14393 npm ERR! argv "C:\Program
Files\nodejs\node.exe" "C:\Program
Files\nodejs\node_modules\npm\bin\npm-cli.js" "run" "start:dev"
npm ERR! node v7.0.0 npm ERR! npm v3.10.8 npm ERR! code ELIFECYCLE
npm ERR! web.facundolarocca.com#0.1.0 start:dev: babel-node
server/server.js npm ERR! Exit status 1 npm ERR! npm ERR! Failed at
the web.facundolarocca.com#0.1.0 start:dev script 'babel-node
server/server.js'. npm ERR! Make sure you have the latest version of
node.js and npm installed. npm ERR! If you do, this is most likely a
problem with the web.facundolarocca.com package, npm ERR! not with npm
itself. npm ERR! Tell the author that this fails on your system: npm
ERR! babel-node server/server.js npm ERR! You can get information
on how to open an issue for this project with: npm ERR! npm bugs
web.facundolarocca.com npm ERR! Or if that isn't available, you can
get their info via: npm ERR! npm owner ls web.facundolarocca.com
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Projects\web.facundolarocca.com\npm-debug.log
I guess I should tell to babel to avoid compiling those kinds of files, but I cant find how neither other solution. I ended up following the simples tutorial I've found: Server Rendering - Redux
I removed the whole server-code because I thought I was cleaner, but If think I should include it, feel free to ask me.
Thanks.

Resources