Setting custom directory for server files for Next.js - javascript

Rather than in the root directory, I want to keep all my backend related files inside a folder named 'server'. The problem is now the frontend won't load properly as it can't find the 'pages' directory. I remember there was a way to set the directory somehow when initializing the app but I don't remember the specifics. Can someone please help me with this?
server/index.js:
const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({
dev,
// some config property that I don't remember
})
app.prepare().then(() => {
const server = express()
server.listen(3000, () => console.log('> Ready on http://localhost:3000'))
})

You can read from the documentation:
The next API is as follows:
next(opts: object)
Supported options:
dev (bool) whether to launch Next.js in dev mode - default false
dir (string) where the Next project is located - default '.'
quiet (bool) Hide error messages containing server information - default false
conf (object) the same object you would use in next.config.js - default {}
Then, change your start script to NODE_ENV=production node server.js.
It is dir option.

Related

Electron store my app datas in 'userData' path

I'm building and trying do deploying a packaged electron app. FOr the packaging i used
electron-packager
electron-installer-debian
electron-installer-dmg
electron-winstaller
and I'm facing a little issue where I have to store tha appa datas somewhere in my user computer.
I saw that the good practice is to use the the folder in the path that is returned by the electron method app.getPath('userData').
from the docs
It is The directory for storing the app's configuration files, which by default it is the appData directory appended with the app name.
%APPDATA% on Windows
$XDG_CONFIG_HOME or ~/.config on Linux
~/Library/Application Support on macOS
By my tests sometimes this folder is not created automatically when the app is installed and other times yes and I'm wondering if i should create it or not.
Right now i'm quitting the app if this folder isn't present in the pc with the following code
var DatasPath = app.getPath('userData')
if (!fs.existsSync(DatasPath)){
process.exit()
}
So the question is
should i create the DatasPath folder with fs.mkdirSync(DatasPath); when it is not present or it is 'bad practice to do so', and if I can create the folder i have to warning the user the i have just added that folder?
(Expanding my reply from a "comment" to an "answer")
i don't know if i'm supposed to create it or not so i automatically
make the app quit if there is not that folder
It seems you are taking "userData" too literally? It is not an actual "folder" named "userData – it is a path to where the operating system stores data for that application. Electron currently runs on 3 operating systems and each one does things differently. For our convenience, Electron hides those differences by creating the wrapper method app.getPath(name) so the same code will work on each OS.
Try this: put the line below in your main.js script:
console.log(app.getPath('userData'));
/Users/*********/Library/Application Support/MyCoolApp
(the "*********" will be your user account name.)
UPDATED:
Run the code below in main.js and then look in the folder specified by the "userData" path
const fs = require("fs");
const path = require('path');
var datasPath = app.getPath('userData')
var data = "I am the cheese"
var filePath = path.join(datasPath, "savedData.txt")
fs.writeFileSync(filePath, data)
At pathConfig.js
function getAppDataPath() {
switch (process.platform) {
case "darwin": {
return path.join(process.env.HOME, "Library", "Application Support", "myApp");
}
case "win32": {
return path.join(process.env.APPDATA, "myApp");
}
case "linux": {
return path.join(process.env.HOME, ".myApp");
}
default: {
console.log("Unsupported platform!");
process.exit(1);
}
}
}
const appPath = __dirname;
const appDataPath =
!process.env.NODE_ENV || process.env.NODE_ENV === "production"
? getAppDataPath() // Live Mode
: path.join(appPath, "AppData"); // Dev Mode
if (!fs.existsSync(appDataPath)) {
// If the AppData dir doesn't exist at expected Path. Then Create
// Maybe the case when the user runs the app first.
fs.mkdirSync(appDataPath);
}
In each operating system the appData folder has a different path and the perfect way of getting this path is by calling app.getPath('userData') in the main process.
But there is a package that can handle this for you, it stores data in a JSON file and update it in every change.
In my opinion this package is much better than handling everything by your self.
Read more :
https://www.npmjs.com/package/electron-data-holder

process.env.NODE_ENV returns undefined in webpack 4, server-side

in server code I have this:
import express from "express";
const server = express();
import path from "path";
// const expressStaticGzip = require("express-static-gzip");
import expressStaticGzip from "express-static-gzip";
import webpack from "webpack";
import webpackHotServerMiddleware from "webpack-hot-server-middleware";
import configDevClient from "../../config/webpack.dev-client";
import configDevServer from "../../config/webpack.dev-server.js";
import configProdClient from "../../config/webpack.prod-client.js";
import configProdServer from "../../config/webpack.prod-server.js";
const isProd = process.env.NODE_ENV === "production";
const isDev = !isProd;
const PORT = process.env.PORT || 8000;
let isBuilt = false;
const done = () => {
!isBuilt &&
server.listen(PORT, () => {
isBuilt = true;
console.log(
`Server listening on http://localhost:${PORT} in ${process.env.NODE_ENV}`
);
});
};
if (isDev) {
const compiler = webpack([configDevClient, configDevServer]);
const clientCompiler = compiler.compilers[0];
const serverCompiler = compiler.compilers[1];
const webpackDevMiddleware = require("webpack-dev-middleware")(
compiler,
configDevClient.devServer
);
const webpackHotMiddlware = require("webpack-hot-middleware")(
clientCompiler,
configDevClient.devServer
);
server.use(webpackDevMiddleware);
server.use(webpackHotMiddlware);
console.log("process.env.NODE_ENV",process.env.NODE_ENV);//RETURNS UNDEFINED
server.use(webpackHotServerMiddleware(compiler));
console.log("Middleware enabled");
done();
} else {
webpack([configProdClient, configProdServer]).run((err, stats) => {
const clientStats = stats.toJson().children[0];
const render = require("../../build/prod-server-bundle.js").default;
server.use(
expressStaticGzip("dist", {
enableBrotli: true
})
);
server.use(render({ clientStats }));
done();
});
}
I client and server config files I have this plugin enabled:
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("development"),
WEBPACK: true
}
but this is the output
process.env.NODE_ENV undefined
Server listening on http://localhost:8000 in undefined
in client side it is working BUT express side process.env.NODE_ENV returns undefined
Assuming you using Webpack-Dev-Server, you can use this call syntax witch is proper :
const dev = Boolean( process.env.WEBPACK_DEV_SERVER )
You will no longer need to pass environment type parameters, because I think you pass parameters in your script run in packages.json
I'm writing my experience to help anyone out there with this problem, though I did not actually solve it. I had the same problem with setting the environment variables in my server-side project.
apparently, after you set the environment variables they are completely accessible in the building process, which is in the build tools like webpack config or even .babelrc.js.
but after the build process, the environment variables get overwritten AND there is a time gap between build process and overwriting environment variables.
I used many webpack or babel plugins but neither of them could hold on to environment variables after the build process ON the server-side but they were immediately defined on the client-side.
since I'm using ReactJs, I tried adding REACT_APP_ to the beginning of variables, but still no luck.
some other plugins I used: webpack dotenv, webpack.DefinePlugin, webpack.EnvironmentPlugin, babel-plugin-transform-define, babel-plugin-transform-inline-environment-variables
so it made me use the good old-fashion way of setting environment.js on DEPLOY but not on the BUILD process.
in case someone is not familiar: you have one main environment.js and (in my case) 2 other files, one for staging environment.staging.js and one for production environment.prod.js. On each deploy, you copy the related js to environment.js, the main environment file, and in your code, you always read global CONSTs,baseUrl for APIs and ... from environment.js.
hope it helps someone out there.

NextJS deploy to a specific URL path

I am working on my first NextJS application. When I run "npm run dev" or "npm run start" it deploys my application to
http://host:port/
When I navigate to a page the url becomes
http://host:port/page1
I need to have my own specific URL, such as
http://host:port/my-test-application/path-for-my-app/
http://host:port/my-test-application/path-for-my-app/page1
Furthermore, my app has a lot of elements to link to other areas of the applications, i need these to also go to URL with the basePath and not just go to the root path.
I will also be depolying this app to different servers which will have different basePaths, therefore this can not be hardcoded in my app.
How can I do this?
With other applications such as react/vue/angular/native JS, I simply build my application and put the build code in a "my-test-application/path-for-my-app" folder on my server.
I tried this with my NextJS application but i got an error that ".next" folder could not be found.
I googled and could find some references to using "assetPrefix" or using "Zones". However I do not really understand what I am supposed to do.
How do i get my app deployed to specific URL
Solution 1: Restructure "pages" - Does not enable me to deploy to different servers with different basePaths
I could create the folder structure inside my "pages" directory and change all my elements to use this folder structure.
|- pages
|- my-test-application
|- path-for-my-app
|- index.js
|- page1.js
<Link href="/my-test-application/path-for-my-app/page1" >
I dislike this solution as the basePath is hardcoded into my application, as to apposed to a deployment setting.
If I wanted to deploy my app on 2 servers with different basePaths (i.e. below) I would have to have 2 versions of the code.
http://host:port/my-test-application_1/path-for-my-app/page1
http://host:port/my-test-application_2/diff-path-for-my-app/page1
Updated: I have updated this question on 5th March to include my need for s to work and one solution which I do not like.
In Next.js ≥ 9.5, you can set a basePath in your next.config.js. For example, if you want your entire Next.js app to live at /docs, you can use:
// next.config.js
module.exports = {
basePath: '/docs'
}
Next will will make sure all assets are served from the right place, and it will automatically prefix this base path for all Links in your app, as well as during programmatic navigation using next/router. For example,
<Link href="/about">
<a>About Page</a>
</Link>
will be transformed to link to /docs/about, as will
router.push('/about')
This means that you can change basePath without changing anything at all in the actual code of your app.
I found a solution using NGINX to reverse proxy a URL with the base path.
Useful links
https://levelup.gitconnected.com/deploy-your-nextjs-application-on-a-different-base-path-i-e-not-root-1c4d210cce8a
https://www.docker.com/blog/tips-for-deploying-nginx-official-image-with-docker/
Application Changes
Dependencies
next-images : in order to import static images from "public" when using a reverse proxy
#zeit/next-css : in order to use stylesheet files
as well as usual NextJS dependencies
next.config.js
Add a "next.config.js" file at the root of your application so that you can specify the "assetPrefix" and "publicRuntimeConfig.basePath"
assetPrefix : used by NextJS when accessing components, stylesheets, pages etc
publicRuntimeConfig.basePath : used in s so specify the prefix to add to the link, used in "src" tags of "" elements when using public images
Example
const isProd = process.env.NODE_ENV === 'production'
// Enable importing of css stylesheets
const withCSS = require("#zeit/next-css");
const withImages = require('next-images');
/*
* Gets the BASE_PATH from the command used to start this app.
* If BASE_PATH is specified but it does not start with a "/"
* then add it.
*/
function getBasePath() {
var basePath = ''
if (isProd && process.env.BASE_PATH){
if (process.env.BASE_PATH.startsWith("/") ){
basePath = process.env.BASE_PATH;
} else {
basePath = "/" + process.env.BASE_PATH;
}
}
console.log("getBasePath() : isProd = " + isProd);
console.log("getBasePath() : basePath = " + basePath);
return basePath
}
module.exports = withCSS(withImages({
assetPrefix: getBasePath() ,
publicRuntimeConfig: {
basePath: getBasePath() ,
},
}));
Static images
Use "next-images" in order to import the images and reference the imported object in the 's src tags
Change any references to your static images (those in /public folder) to have the base path prefix. For example my "Footer" component has the following
import '../stylesheets/main.css';
import img1 from '../public/image_name1.png'
import img2 from '../public/image_name2.png'
export default class o extends React.Component {
render(){
var prefix = publicRuntimeConfig.basePath
return (
<div >
<a className="icon" href="http://www.image_name.com" >
<img src={img1} alt="image_name1"/>
</a>
<a className="icon" href="http://www.image_name2.com">
<img src={img1} alt="image_name2"/>
</a>
</div>
);
}
}
Note: I tried to use the publicRuntimeConfig.basePath as a prefix to the src URL (as below), but this did not work in my deployed environment (see below)
import getConfig from 'next/config'
const { publicRuntimeConfig } = getConfig()
...
...
<a className="icon" href="http://www.image_name.com" >
<img src={`${publicRuntimeConfig.basePath}/image_name1.png`} alt="image_name1"/>
</a>
Links
Change your Link's to use the base path prefix, for example in my "Header" component i have the following
import Link from 'next/link';
import '../stylesheets/main.css';
import getConfig from 'next/config'
const { publicRuntimeConfig } = getConfig()
const detailId1 = "banana"
const Header = () => (
<div>
<div>
<Link href={`${publicRuntimeConfig.basePath || ''}/`}>
<a className="linkStyle">Home</a>
</Link>
<Link href={`${publicRuntimeConfig.basePath || ''}/about`} >
<a className="linkStyle">About</a>
</Link>
<Link href={`${publicRuntimeConfig.basePath || ''}/details/[id]`}
as= {`${publicRuntimeConfig.basePath || ''}/details/${detailId1}`} >
<a className="linkStyle">Details Var 1</a>
</Link>
</div>
</div>
);
export default Header;
Note: In the blog https://levelup.gitconnected.com/deploy-your-nextjs-application-on-a-different-base-path-i-e-not-root-1c4d210cce8a, it contains a "Link.tsx" that does the adding of the prefix for you, so you simply use that Link component (import Link from "./Link.tsx";) and not the nextJS version (import Link from 'next/link';). However, that "Link.tsx" does not work for me when I have variables in my link URLs.
Running your nextjs app
When running your application locally when you do NOT want a base path you can just running
npm run dev
As no BASE_PATH is specified your application should be accessible from "http://localhost:3000" and your src values should be "/image_name1.png" and when you hover over your s you will see the link is "http://localhost:3000/pagename"
When you want to run with a base path do the following
export BASE_PATH=a/b
npm run dev
Note: for some reason in my environment if i specify "export BASE_PATH=/a/b" (/ at the start of the path) I get a folder directory added to the beginning of the path. Therefore i specify it without the starting / and the code in next.config.js adds the starting / if need be.
You can not access your app at "http://localhost:3000" as you have the base path/assetPrefix/publicRuntimeConfig.basePath set. Now you need a reverse proxy.
NGINX : Reverse Proxy
I found the easiest setup was to use a NGINX docker image. You need to run NGINX with a configuration containing the redirection to your NextJS app.
Create a folder and add in that folder a "default.conf" file. Make sure the path you put in your "location" is the SAME path you specified for BASE_PATH when starting your nextjs app.
server {
listen 80;
server_name localhost;
location /a/b/ {
proxy_pass http://myhost:3000/;
}
}
Important Notes:
you have to have the trailing / on the end of your proxy_pass URL otherwise additional paths are not passed onto your NextJS apoplication
if you use a variable in the location you must make sure you include passing on the paths
example
location ~ /a/b/(.*)$ {
set $upstream http://myhost:3000/$1;
proxy_pass $upstream;
}
In a command prompt from that directory run a NGINX docker image, telling it to use your config file.
docker run --name mynginx1 -v C:/zNGINX/testnginx/conf:/etc/nginx/conf.d -p 80:80 -d nginx
name of the docker container is "mynginx1"
the v parameter is telling it to copy any files in "C:/zNGINX/testnginx/conf" on your computer to the "/etc/nginx/conf.d" directory in the docker container. This will copy your "default.conf" to the docker container and NGINX will read that configuration file.
Note: Make sure you have the "conf.d" in your path for the docker location (":/etc/nginx/conf.d"), blogs I read did not include this part, it only specified ":/etc/nginx/", and without it the image doesn't start.
the p parameter is telling to run NGINX on port 80
Go to the following URL
http://localhost:80/a/b/
NGINX will redirect that URL to "http://localhost:3000". Therefore your application should now be accessible from the URL with the base path. Clicking on s should work, the link should contain the base path which goes to NGINX which redirects back to the application stripping off the base path leaving any other paths.
Real World Server Deployment using Docker
If you are deploying your application to a server, as apposed to running locally, you can build your application and then copy the relevant files/folders to the server machine. Make sure you have the BASE_PATH set when both building and running your app
export BASE_PATH=a/b
npm run build
cp package*.json [server_location]
cp next.config.js [server_location]
cp ./next [server_location]
then on that server location run
npm install
export BASE_PATH=a/b
npm run start
Note: If you have images in "public" that you reference in your app, use "next-images" and import the image rather than use the publicRuntimeConfig.basePath as a prefix. When i did the latter the images were not found. See the section about about images for examples.
To add to the answers here, simply using basePath is not enough. basePath works very well for automatically pointing links, but it does not do anything to static files served from public directory.
For example you have public/img/my-img.png that you referred in your img or Image element as <img src="img/my-img.png" /> or <Image src="/img/my-img.png" />, you have to change it to <img src="your-sub-path/img/my-img.png" /> or <Image src="/your-sub-path/img/my-img.png" /> respectively.
You can use custom server to create NextJS application work on your specific URL:
See the example here:
https://github.com/zeit/next.js/tree/canary/examples/custom-server-express
The key point is to add your specific url as an API, then forward user's request to your specific page you want to serve:
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.get('/my-test-application/path-for-my-app', (req, res) => {
return app.render(req, res, '/index', req.query)
})
server.get('/my-test-application/path-for-my-app/page1', (req, res) => {
return app.render(req, res, '/page1', req.query)
})
server.get('/posts/:id', (req, res) => {
return app.render(req, res, '/posts', { id: req.params.id })
})
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
To me, all the solutions mentioned is too much trouble for me, so i rolled the following way.
next.config.js
module.exports = {
basePath: '/drh',
}
_app
You can overwrite the _app.js file.
export default function App({ Component, pageProps }) {
return <Component {...pageProps} base="/drh" />
}
This way all pages will have a prop base hard coded.
export default function Index({ base }) {
return <img src={`${base}/images/hooks-logo.png`}/>
}
context
if you don't want to push this base to all children using a prop, this is the place you can use a context. The context provider can be setup in the _app.js as well.
seems to me one of a good entry point to nextjs app is _app.js, verse a typical react app is index.js.
I solved it like this, by writing a redirect in next.config.js:
const withImages = require('next-images')
module.exports = withImages(withSass({
cssLoaderOptions: {
url: false
},
//Might need to change it here, before going to the production environment.
assetPrefix: 'http://localhost:3000',
postcssLoaderOptions: {
config: {
ctx: {
theme: JSON.stringify(process.env.REACT_APP_THEME)
}
}
}
}));

Simple and elegant way to override local file If exists?

Looking for elegant and simple solution to have "local configuration override" files.
The idea is to be able to have local configuration that will not ask to be added to git repository every time.
For that I need to include local.config.js if it exists.
I have global app configuration in config.js with configuration like
export const config = {
API_URL="https://some.host",
}
and config.local.js
export const config = {
API_URL="https://other.address",
}
there's .gitignore:
config.local.js
Difficulty:
I do not want to add a node module to project just for this one thing. I believe there should be an elegant way to do this in one or few lines, but have not found any so far.
Things that I tried:
1.
try {
const {
apiUrl: API_URL,
} = require('./config.local.js');
config. API_URL =apiUrl;
} catch (e) {
}
require does not work inside try{} block.
2.
const requireCustomFile = require.context('./', false, /config.local.js$/);
requireCustomFile.keys().forEach(fileName => {
requireCustomFile(fileName);
});
does not work.
3.
export const config = require('./config.local.js') || {default:'config = {...}'}
does not work.
4.
Using .env and settings environment variable: I need to override whole array of configuration values. Not one by one.
This solution uses process.argv. It is native to node as documented here and does not use .env
It inspects the command values used to start the app. Since these should be different between your local and production environments, it's an easy way to switch with no additional modules required.
command prompt to start your node app:
(this might also be in package.json and incurred via npm start if you're using that approach.)
$ node index.js local
index.js of your node app:
var express = require('express');
var config = require('./config');
if (process.argv[2] === 'local') {
// the 3rd argument provided at startup (2nd index) was 'local', so here we are!
config = require('./config_local');
}
var app = express();
// rest of owl…

Setup app production and developent mode in node.js

In my node app, I want to set production and development in my config.js file.
For that I have all most set all thing but I'm still missing something.
I want to get config data like database credential from config file based on my development mode. If I upload on live then app will use live cred. On other hand if I used local then it should be use local cred.
module.exports = function () {
console.log("Process env is ::: ", process.env.NODE_ENV);
if (process.env.NODE_ENV == 'production') {
return {
db : {
host:'localhost',
batabase:'dbname',
username:'',
password:''
}
}
} else {
return {
db : {
host:'localhost',
batabase:'dbname',
username:'',
password:''
}
}
}
};
I have taken ref from this answer
Just try this way.
module.exports = (function () {
process.env.NODE_ENV='development';
if(process.env.NODE_ENV === 'production'){
// Config data of Live
}else{
//Config data of Local
}
})()
This works for me. :)
process.env refers to the Environment Variables exists at the time you start you nodejs app . (it's part of the os)
When you deploy to cloud , usually it's handled for you already (process.env.NODE_ENV = production) .
Some cloud providers even give you the option to control it via a GUI .
But for local environment , you can use .dotenv package . (https://github.com/motdotla/dotenv)
With this package you create a .env file at the top of your project ,
and just write down NODE_ENV = local/staging/production
Please note that you can always run in shell:
export NODE_ENV=production
(WATCH FOR WHITESPACES !)
before you start you nodejs app which will also give you the effect
of controlling process.env
Using the config files in other files, just by requiring it .
const config = require('path/to/config.js');
then config.data.host will be changed depend on the NODE_ENV

Categories