I am just starting to figure out nodejs and I forgot to put in the flag for session support
$ express -s somefolder
Can I run the above command without overwriting anything I already added or changed or do I have to do something else?
it is not as clear as adding a new dependancy (stylus) to package.json and rerun $ npm install
Update:
Session support is now added via the expressjs/session module.
To install:
npm install -save express-session
To use:
import * as session from "express-session";
...
app.use(cookieParser());
app.use(session({ secret: "..." });
Be sure to visit the module on GitHub to get the latest installation and usage instructions.
Original answer:
Just add the session middleware to your Express app.js file.
app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
Make sure it comes after the express.cookieParser() call. Also, update the secret value to a random string for security.
Related
I have inherited a project where currently the front end docker container is setup as below.
Let me also start by saying I am sure this is a trivial question but I am a bit new using Angular/Express/Nodejs.
FROM node:18.12.1
# Copy dependency definitions
COPY package.json /app/
WORKDIR /app
# Install dependecies
RUN npm install
# copy artifact build from the 'build environment'
COPY dist /app/public
COPY express /app
# COPY views /app/views
# Default environment variable for local testing
EXPOSE 80
# serve the appliction
CMD ["node", "server.js"]
In this setup the front end also contains an express folder which is referenced below by the line calling
COPY express /app
Express then has a server.js file which creates the typical express boilerplate. In this configuration the session is setup as follows:
var app = express();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(session(
{
resave: true,
saveUninitialized: true,
cookieName: 'session',
secret: 'random_secret',
duration: 15 ,
activeDuration: 15,
maxAge: 30
}));
Is this a huge vulnerability having the secret just stored in the code like this?
I have a similar configuration in the backend for Nodejs where express sets the secret but that secret is stored as an enviroment file.
Again my apologizes if this is obvious.
Yes, this is a major security problem. Anyone who has a copy of the image can find the credential in plain text in your source code; if you've committed it to source control, it will also be there. Since it's in your source code, if you do discover that the key is compromised, you need to get a code change reviewed and tested and deployed to change it.
The other major problem here is that every instance of your application now shares the same secret. If this secret is to encrypt a session cookie, it's possible that someone else is running a different copy of the application, but then can extract the session cookie from their copy and send the session to yours, even if they don't know the encryption key per se. That can potentially let them get access to data on your system they're not supposed to.
Credentials, signing keys, and host names, should always be passed at runtime. In Docker the easiest way to do this is via environment variables. Do not create a .env file in a Dockerfile or use Dockerfile ENV statements; these contents can be very easily extracted from the image. Injecting a .env file using Compose volumes: or env_file: should be safe for most uses.
I have a split app using nestjs on the server and an Angular app as the client. Setting up websockets with socket.io seemed pretty easy using the #nestjs/websockets module and on the client I used ngx-socket-io. I used this repo as basis. Now when I update the project's #nestjs/websockets dependency to the latest version I get
CORS errors and
an error that the client couldn't load the socket.io client js file
I expected CORS problems and after the update, I could fix them by adding
app.enableCors({
origin: 'http://localhost:4200',
credentials: true,
});
to my main.ts file, but I don't know why the client file is not served. With the version of the repo (5.7.x) there are neither CORS errors nor problems with serving the file.
I tried a couple of settings of #WebSocketGateway(), moving to a different port, setting serveClient (even though it should be true by default), but nothing seemed to work. Any advice?
thanks
In my case
I replaced
app.useWebSocketAdapter(new WsAdapter(app));
from
import { WsAdapter } from '#nestjs/platform-ws';
with
app.useWebSocketAdapter(new IoAdapter(app));
in main .ts from
import { IoAdapter } from '#nestjs/platform-socket.io';
Worked like a charm!
The problem was that nestjs did separate the lower level platform (socket.io, express, fastify, ...) from the nestjs modules. The websocket module requires to install an underlying platform, for socket.io
npm install --save #nestjs/platform-socket.io
To serve the socket.io client file it seems like there also needs to be an HTTP platform installed, for express
npm install --save #nestjs/platform-express
More info in the migration guide for v6.
I had the same problem. i was opening the client side of the application in the web-browser, but directly from my filesystem (i would double click on the file index.html next to the little dummy fake-front-end.js on my desktop for example...). It seems that the CORS problem would persist until i actually accessed the index.html through a proper server. So i created a route on my backend, to serve the index.html, and the fake-front-end.js.
There is a section about CORS on the socket.io officual documentation. And there is a section on the nestjs website, but both didnt really helped in my case.
This took me a while to figure out, so I figure I'd leave some instructions on how I got it done in case someone else runs into the same problems.
I needed to allow directory access to the .well-known directory in Express to be able to use certbot to generate SSL certificates.
Install the serve-index package from npm
npm install serve-index
Import it
var serveIndex = require('serve-index');
Then declare the middleware
app.use('/.well-known', express.static('.well-known'), serveIndex('.well-known'));
on WINDOWS ...after install express-seed and node.js for the "blog" tutorial, i get the same cmd prompt after typing node app.js.
another time i got body parser and error handling errors
i tried alot of solutions, even had a local host run with another tutorial, but i would like to run from the blog tutorial due to some slight differences of the set-up.
Of course im a newb, and i know theres tons of answers on the forum, but none are correcting my issue...please help.
and everytime i try to post my report on here it errors me saying i have to indent each line 4 spaces. im just losing in general.
Is there a step im missing? all the tut's say just do 'this' and 'this' and i have a local host running so i can make changes to views. any help?
// Module dependencies.
var express = require('express');
var app = express.createServer();
// Configuration
app.configure( function() {
});
// Routes
app.get('/', function(req, res) {
res.send('Hello World');
});
app.listen(3000);
what version of node & express are you running?
From the command line you can check with:
node --version
and
express --version
From your code, it looks like an older version of express (version 3 or less), but I'm betting you didn't specify the version on the npm install, which will give you the latest version (4+). There's a lot of breaking changes between those versions, so you can't run old code with the new framework successfully. My bet is that your blog tutorial hasn't been updated to express 4.x yet.
What I would like to do is add the following to me already running coffeescript written server
app.get '/test.js', (req, res) ->
render coffee somecoffeefile.coffee
Is something like this possible with NodeJS, Express, and Coffeescript?
Thanks!
Jose
Good news: This is already comes with Connect (and therefore Express, which extends Connect) as a plugin! It's not well-documented; in fact, I wrote something similar myself (connect-coffee) before I was informed that such a thing already existed.
Here's how you'd go about setting it up with Express:
# Notice the following code is coffescript
# You must add the parens for the app.use method to use in js
coffeeDir = __dirname + '/coffee'
publicDir = __dirname + '/public'
app.use express.compiler(src: coffeeDir, dest: publicDir, enable: ['coffeescript'])
app.use express.static(publicDir)
Now when, say, http://yourapp/foo.js gets requested, if no such file exists in your public directory, foo.coffee will automatically be compiled, and the resulting foo.js will be served. Note that it's important for static to be set up after compiler.
Update: As of Connect 1.7, the compiler middleware has been removed. Partly because of that, and partly to provide a more Rails 3.1-like experience, I've created a new middleware called connect-assets. Install it with npm, then set it up like so:
app.use require('connect-assets')(directory)
where directory is the folder your CoffeeScript files are in (the default is assets). Simple, right? Try it out and let me know what you think.
CoffeeScript = require 'coffee-script'
app.get '/test.js', (req, res) ->
render CoffeeScript.compile coffeeSourceCode
For some reason, the compiler isn't working anymore, so I did this:
fs = require 'fs'
coffee = require 'coffee-script'
app.use express.static "#{__dirname}/static"
app.get '/:script.js', (req, res) ->
res.header 'Content-Type', 'application/x-javascript'
cs = fs.readFileSync "#{__dirname}/coffee/#{req.params.script}.coffee", "ascii"
js = coffee.compile cs
res.send js
Now you can code up coffee/animal.coffee and in your html, do a standard script src='/animal.js'. This hides the implementation detail. The coffeescript is not accessible because "/coffee" dir is not exposed as a static path.
Notes:
This is, of course, a CoffeeScript Node app. I assume if you're using CS for client scripts, you're using it for your server too!
The "static" line is optional. My point is you can happily keep "js" files in the static dir, e.g. library files like jquery.min.js.
Like most Node/Express examples, this is good for development; but for production, you should send cache headers, compress it, and ideally some form of reverse-proxying to avoid reading the file and compiling it each time.
For those of us using the latest version of Connect and Express, I've just published a new module, npm install connect-coffee-script, which compile coffee script files on the fly. Documentation and a sample are provided as well as an introduction article.
Here's an exemple from the readme:
var coffeescript = require('connect-coffee-script');
var connect = require('connect');
var app = connect();
app.use(coffeescript({
src: __dirname,
dest: __dirname + '/public',
bare: true
}));
app.use(connect.static(__dirname + '/public'));
app.listen(3000)
If you would like to use a great existing plugin I would recommend Trevor Burnham's Connect-Assets. It helps compiling, minifying and concatenating .js and .coffee-files and optimizes how the files are being served (a far-future expires header with invalidation using the file's md5-hash). Well written plugin.
coffee-middleware did exactly what I wanted to - minimal setup, no generated files, and not sloppy.
When it gets a request for somescript.js it will check if there is a somescript.coffee. If there is, it will compile it and send it over.
Install it:
npm install coffee-middleware
To use, just add
app.use require('coffee-middleware') src: "#{__dirname}/your/web/root"
before whatever you use to serve static files.
Simple example that serves files in a "public" directory, complies coffeescript before sending it over, and does colored logging:
app = require('express')()
app.use require('morgan') 'dev'
app.use require('coffee-middleware') src: "#{__dirname}/views"
app.use require('serve-static') "#{__dirname}/views"
app.listen 80
To use above code:
mkdir coffeeServer
cd coffeeServer
npm install morgan coffee-middleware serve-static
npm install coffee-script -g
echo 'app = require("express")()
app.use require("morgan") "dev"
app.use require("coffee-middleware") src: "#{__dirname}/views"
app.use require("serve-static") "#{__dirname}/views"
app.listen 80' > server.coffee
coffee -c server.coffee
mkdir views
cd views
echo 'console.log "Hello world!"' > script.coffee
cd ..
node server.js
You can copy the whole bunch into the terminal and it will setup and run the server.
To test:
curl XXX.XXX.XXX.XXX/script.js
That last bit should spit out
(function() {
console.log("Hello world!");
}).call(this);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NyaXB0LmpzIiwic291cmNlcyI6WyJzY3JpcHQuY29mZmVlIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQUEsRUFBQSxPQUFPLENBQUMsR0FBUixDQUFZLGNBQVosQ0FBQSxDQUFBO0FBQUEifQ==NHS0076
Good luck!
I think you should compile COFFEE files only once, especially with production mode
If you want use coffee with Express 3, or with any web framework look to this repo ExpressOnSteroids You can use this solution, or create your own with Cakefile from this project
You can use Coffee4Clients to render coffee assets to javascript on the fly with your express server.
Update: Coffee4Clients has been killed in favour of DocPad which pre-compiles your assets.