Created
June 1, 2019 20:19
-
-
Save xeoncross/61e177b207875952288bfe37912a0d51 to your computer and use it in GitHub Desktop.
Example of using chromedp to prerender a create-react-app frontend using fake SSR via chrome headless
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"io/ioutil" | |
"log" | |
"strings" | |
"testing" | |
"github.com/chromedp/cdproto/dom" | |
"github.com/chromedp/chromedp" | |
) | |
func TestSSRofCRA(t *testing.T) { | |
// create context, this would come from client if using HTTP | |
ctx, cancel := chromedp.NewContext(context.Background()) | |
defer cancel() | |
// create-react-app uses port 3000 by default | |
var res string | |
err := chromedp.Run(ctx, scrapIt("http://localhost:3000/", &res)) | |
if err != nil { | |
t.Fatal(err) | |
} | |
ioutil.WriteFile("rendered.html", []byte(res), 0664) | |
log.Println(strings.TrimSpace(res)) | |
} | |
func scrapIt(url string, str *string) chromedp.Tasks { | |
return chromedp.Tasks{ | |
chromedp.Navigate(url), | |
chromedp.ActionFunc(func(ctx context.Context) error { | |
node, err := dom.GetDocument().Do(ctx) | |
if err != nil { | |
return err | |
} | |
*str, err = dom.GetOuterHTML().WithNodeID(node.NodeID).Do(ctx) | |
return err | |
}), | |
} | |
} | |
// Alternative, less-stable fetch using chrome directly | |
// out, err := exec.Command("sh", "-c", "/root/tools/chromium-latest-linux/latest/chrome --headless --no-sandbox --dump-dom "+url).Output() | |
// if err != nil { | |
// log.Fatal(err) | |
// } | |
// fmt.Printf("%s\n", out) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.reddit.com/r/golang/comments/bvnzd3/how_do_you_guys_handle_javascript_frontends/
https://www.reddit.com/r/reactjs/comments/bvnkp8/react_framework_for_both_web_and_mobile_with/
Google Search and JavaScript Sites (Google I/O'19): https://www.youtube.com/watch?v=Ey0N1Ry0BPM
https://hackernoon.com/whats-new-with-server-side-rendering-in-react-16-9b0d78585d67