I looked at csrf implementation in node js Git hub example and was wondering this is for a application level. What if I want to apply it on one or two pages in the application. I did not find any example on the web. I know that in asp.net you can do it but not sure how the same can be achieved in Node JS.
Any help in guiding to a solution is greatly appreciated.
Add the csruf middleware on the routes which you want to protect. Like the example in the Github link shows:
app.get('/route/to/protect', csrfProtection, function (req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
This will allow csrf only for this route and not others. You can also use Regex to match routes as explained in the express docs.
Related
I am currently on Next js using full static generation, as I want to serve all my pages from the S3 + cloudfront (no server involved). Next js has good support for this except when it comes to dynamic pages (ex: /posts/:id). All the framework features to solve this type of scenario involve either rendering all passible pages at build time (which is not viable) or having a server to render these pages that have dynamic routes (making, therefore, the site an hybrid app).
To continue to be full static I need to have a way around this.
In create react app one could use the react-router and resolve the routes on the client side, which is exactly what I want to do for the dynamic routes. But I as far as I know next js and the react-router are not compatible, so apparently that is not an option.
Based on what I know, I think Dynamic Route on SSG is supported. Dynamic route feature is independent of getServerSideProps or getStaticProps. you can just use next/router to get the param you need and render your page accordingly.
Here is the official example.
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
return <p>Post: {pid}</p>
}
export default Post
Reference
https://nextjs.org/docs/routing/dynamic-routes
I am using React Router 4.0 and Express 4.14 to create an app that has a mix of single-page-app (SPA) and multi-page-app (MPA). I don't know if that's good practice, but this is not the point. I am actually doing it to learn rather than for a real world app. This idea comes from the scenario where you have strongly separated sections inside an app, as for example a blog and a portfolio.
Client side
So, when I want to navigate as a SPA, I use the Link component from react-router-dom, like <Link to="/reactrouter-route">. If I want to make a request to a route handled by the server, I use <a href="/server-route">.
Server side
I have a middleware logging the path of any request received by my server. I define two routes, each serving a complete SPA. To keep with the blog/portfolio example, imagine I have the following
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log(req.path);
next();
});
app.get('/', (req, res) => {
res.sendFile('blog.html');
});
app.get('/portfolio', (req, res) => {
res.sendFile('portfolio.html');
});
Behaviour
When I go to / the blog gets loaded as a SPA and I can go to the different posts navigating back to / when I want. Everything works as expected. All this navigation inside the SPA is managed by React Router, and the server only gets the first request to /.
Imagine that from a specific post, say /posts/some-post, I have a link to the portfolio. If I click it, I get a request at the server, and it responds with the portfolio SPA. I can navigate inside the portfolio SPA, but I cannot go back to /posts/some-post. I get the following error:
Cannot GET /posts/some-post
I thought the error was thrown by the server, but surprisingly I don't get any request when going back. I only get requests at the server when going forward through a link (only with <a>).
I kept doing tests and there is no problem if I go back from /portfolio to /. This works as expected.
It gets interesting
I defined a route in my server with just the same rule that I had in my React Router routes. The path I was matching in this new route was /posts/:postid. I set this route to redirect to /. Now, I get the same error if I go from posts/some-post to /portfolio and I try to come back. This is not strange as the server doesn't get a request. It's also normal that I reach / if I go straight to /posts/some-post by typing in the URL in the browser.
But, once I go to /posts/some-post manually, I can go from /portfolio back to /posts/some-post without the error. Now it behaves as if the server was called. In fact, I get a request in the server to fetch the static files. However, I don't get a request to /posts/some-post nor /.
Even then, I would get an error if a go from /posts/some-other-post to /portfolio and try to go back.
Question
I guess this has to do with the cache, but I don't know what is going on there. When is the React Router handling going back? When is the server handlin it? How is the cache involved in this process?
It sounds like you need a clearer mental model of the roles of the server and the client in an SPA. "Single Page" is the important part.
The client, built with React, should never be loading pages from the server. It should be a "single page". In other words, you should not be using <a href="/server-route"> in your client app at all. The client should only get (JSON) data from the server using something like fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
I highly suggest you check out Create React App which also explains how to integrate with a node API backend during development. Basically you want all your client routes to be something like /post/:postid which will be handled by React Router and then that React component would use fetch to get the data from something like /api/posts/10. If you use /api to prefix all your requests to the server it should help your mental model.
Ive created a basic Polymer app from the starter kit (via Yeoman). I've today deployed it to the 'sandbox' on my domain and am getting a strange routing issue. The app is essentially a feed reader.
View app here
When I first visit the app I'm given a blank page whereas locally I'm taken straight to the feed. When clicking on 'News Feed' I'm then taken to the feed as expected.
I've added a route for the path of the domain structure as below but this did not fix it.
You can view the full code of the project here.
routing.html
page('/', function () {
app.route = 'home';
});
page('http://purelywebdesign.co.uk/sandbox/f1feedreader/', function () {
app.route = 'home';
});
I've also tried:
page('/sandbox/f1feedreader/', function () {
app.route = 'home';
});
Any help much appreciated.
Page.js allows you to configure the base path:
page.base('/sandbox/f1feedreader/');
or just use window.location if you don't want to tie is to that specific deployment.
page.base(window.location.pathname);
This is an issue with the way the router page.js works. I assume you were testing with gulp serve (which creates a server and sets the web app base url of "/" to be localhost:3000/). The way you're currently setting your page.js routes is that it's looking exactly after the domain name and not at the "root" of the web directory.
In your case page.js is looking at everything after http://purelywebdesign.co.uk/ (meaning all your routes include should start from sandbox/f1feedreader instead of just /f1feedreader).
The documentation for page.js https://visionmedia.github.io/page.js/ says that it uses regular expressions so you could also update the strings.
I'm trying to redirect front end routes to the admin dashboard, as I'm using the Bolt installation as a REST API back end. Here's how I'm routing the content:
contentlink:
path: /{contenttypeslug}/{slug}
defaults: { _controller: 'Bolt\Controllers\Backend::dashboard' }
requirements:
contenttypeslug: 'Bolt\Controllers\Routing::getAnyContentTypeRequirement'
So, all I've done is use the dashboard controller. When I try to visit one of those routes, I get the following whoops error:
Twig_Error_Loader
Template "dashboard/dashboard.twig" is not defined ()
So for some reason it's not looking in the correct place for the template. Is there a way to correct this?
This looks like it's to do with the Twig path which is setup differently depending on whether there is a frontend or backend request.
you can always add a path to the Twig environment that Bolt uses with the following call:
$app['twig.loader.filesystem']->prependPath("/path/to/twig");
The path to the backend twig templates may vary but usually this will work.
$path = $app['resources']->getPath('app/view/twig');
$app['twig.loader.filesystem']->prependPath($path);
I am having a hard time understanding how exactly node.js serves dynamic content.
So let's say we have the following code that renders a home page:
var express = require('express'),
app = express();
app.get('/', function(req,res){
res.render('home.html');
});
However, let's say this home page was supposed to be a user profile in which you are pulling user information from a database, which results in code:
var express = require('express'),
mongoose = require('mongoose'),
app = express();
mongoose.connect('mongodb://localhost/ExampleDB');
app.get('/:id', function(req,res){
User.findOne({_id: req.id}, function (err, user){
var name = user.name;
var profilePic_uri = user.profilePic_uri;
res.render('home.html');
});
So, ideally home.html is just a template page, in which you set maybe the user's profile picture, their name, etc in the route handler. Right, because the idea behind node, is that this app.js should be able to handle pulling the dynamic content from a database at run time. Where I am having trouble is understanding how exactly rendering dynamic pages work with node. The html page is a static page. You can't really render a php or a asp page because, well, that doesn't really make sense does it?
Which leaves me with the question, how is it done?
If you add...
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
...after app=express() has been done then it will now default to the Jade rendering engine if you don't use an extension. Then in your router:
app.get('/', function(req,res){
res.render('home', {
var1: 'val1',
var2: 'val2'
});
});
You'd need to add Jade to your project's package.json file in the dependencies:
"jade": "~1.9.1",
...and then "npm install" in your folder to bring that in.
Then you'd need a file named /views/home.jade with the contents:
doctype html
html
body
p Var1 is #{var1}
p Var2 is #{var2}
You should see--when you visit your home page--that the values have been passed to the Jade rendering engine and expanded in place in the template as 'val1' and 'val2', respectively.
In your case the page is static. Here comes in play template engines (view engines), with this you can render the content of the page dynamic.
Some of the template engines that I remember right now are vash (it's like razor syntax from MVC, I love it) and jade. There are more of them.
Note: You can find in the links I provided how to integrate them with express.
What you are actually asking is not, how it works in Node, but how Express renders templates. Once you understand that you're actually using a feature of the express module, you're probably more aware of what you need to search for to get the correct documentation.
In short: Express features a template rendering engine that does the job for you, very much similar to what ASP or PHP do.
To get to know Node, I'd advise to try to build something without all the libraries first, just to get to know the platform, and to understand why it's feasible to use such libraries or frameworks (such as express).