Skip to content

Instantly share code, notes, and snippets.

@dmurawsky
Last active May 16, 2019 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmurawsky/606d4464b2cfd0ab3e23325ffa0630da to your computer and use it in GitHub Desktop.
Save dmurawsky/606d4464b2cfd0ab3e23325ffa0630da to your computer and use it in GitHub Desktop.
basic next.js server with stripe
{
"version": 2,
"builds": [
{ "src": "api/*.js", "use": "@now/node" },
{ "src": "package.json", "use": "@now/next" }
],
"env": {
"STRIPE_SECRET_KEY": "@acj_stripe_secret_key"
},
"routes": [{ "src": "/blog/(?<name>[^/]+)$", "dest": "/blog?id=$name" }]
}
const cacheableResponse = require("cacheable-response");
const express = require("express");
const next = require("next");
const bodyParser = require("body-parser");
const keySecret = process.env.STRIPE_SECRET_KEY;
const stripe = require("stripe")(keySecret);
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const ssrCache = cacheableResponse({
ttl: 1000 * 60 * 60 * 72,
get: async ({ req, res, pagePath, queryParams }) => ({
data: await app.renderToHTML(req, res, pagePath, queryParams),
}),
send: ({ data, res }) => res.send(data),
});
app.prepare().then(() => {
const server = express();
server.get("/", (req, res) => ssrCache({ req, res, pagePath: "/" }));
server.get("/about", (req, res) =>
ssrCache({ req, res, pagePath: "/about" }),
);
server.get("/blog/:id", (req, res) => {
const queryParams = { id: req.params.id };
const pagePath = "/blog";
return ssrCache({ req, res, pagePath, queryParams });
});
server.get("*", (req, res) => handle(req, res));
server.use(bodyParser.json());
server.post("/donate", (req, res) => {
stripe.customers
.create({
email: req.body.token.email,
card: req.body.token.id,
})
.then(customer =>
stripe.charges.create({
amount: req.body.amount + "00",
description: "Donation",
currency: "usd",
customer: customer.id,
}),
)
.then(() => res.redirect("/thankyou"))
.catch(err => {
console.log("Error:", err);
res.status(500).send({ error: "Purchase Failed" });
});
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment